<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  
  <title>H5教案</title>

  
  <meta name="author" content="John Doe">
  

  

  

  <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  

  <meta property="og:site_name" content="H5教案"/>

  
  <meta property="og:image" content="/ericxie-book/favicon.ico"/>
  

  <link href="/ericxie-book/favicon.ico" rel="icon">
  <link rel="alternate" href="/ericxie-book/atom.xml" title="H5教案" type="application/atom+xml">
  <link rel="stylesheet" href="/ericxie-book/css/style.css" media="screen" type="text/css">
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
<div class="blog">
  <div class="content">

    <header>
  <div class="site-branding">
    <h1 class="site-title">
      <a href="/ericxie-book/">H5教案</a>
    </h1>
    <p class="site-description"></p>
  </div>
  <nav class="site-navigation">
    <ul>
      
    </ul>
  </nav>
</header>

    <main class="site-main posts-loop">
    
  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/30/mongoose/"><span>mongoose</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/30/mongoose/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-30T12:15:41.000Z">
          2021-01-30
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="mongoose"><a href="#mongoose" class="headerlink" title="mongoose"></a>mongoose</h2><p>mongoose 是node操作mongodb的一个插件</p>
<h3 id="下载安装"><a href="#下载安装" class="headerlink" title="下载安装"></a>下载安装</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i mongoose -S</span><br></pre></td></tr></table></figure>
<h3 id="连接数据库"><a href="#连接数据库" class="headerlink" title="连接数据库"></a>连接数据库</h3><p>useNewUrlParser  使用新的url解析器<br>useUnifiedTopology 使用统一拓扑结构<br>useCreateIndex 使用创建索引  只有创建索引后面才可以让某个字段唯一</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const mongoose=require(<span class="string">&quot;mongoose&quot;</span>);</span><br><span class="line">const Schema=mongoose.Schema;</span><br><span class="line">mongoose.connect(<span class="string">&#x27;mongodb://localhost/game&#x27;</span>,&#123;useNewUrlParser:<span class="literal">true</span>,useUnifiedTopology:<span class="literal">true</span>,useCreateIndex:<span class="literal">true</span>&#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="创建集合"><a href="#创建集合" class="headerlink" title="创建集合"></a>创建集合</h3><p>如果字段仅仅是简单结构，直接设置<br>但是如果遇到复杂字段，例如下面的name除了需要设置type类型外，还需要设置unique标识唯一<br>如果属性是一个对象和数组，可以写成items这个样子</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">const mongoose=require(<span class="string">&quot;mongoose&quot;</span>);</span><br><span class="line">const Schema=mongoose.Schema;</span><br><span class="line">mongoose.connect(<span class="string">&#x27;mongodb://localhost/game&#x27;</span>,&#123;useNewUrlParser:<span class="literal">true</span>,useUnifiedTopology:<span class="literal">true</span>,useCreateIndex:<span class="literal">true</span>&#125;);</span><br><span class="line"></span><br><span class="line">var  PackData=new Schema(&#123;</span><br><span class="line">    name:&#123;<span class="built_in">type</span>:String,unique:<span class="literal">true</span>,index:<span class="literal">true</span>&#125;,</span><br><span class="line">    num:Number,</span><br><span class="line">    items:[</span><br><span class="line">        &#123;name:String,num:Number&#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line">var Pack=mongoose.model(<span class="string">&quot;pack&quot;</span>,PackData);</span><br></pre></td></tr></table></figure>
<h3 id="给集合中插入一条信息"><a href="#给集合中插入一条信息" class="headerlink" title="给集合中插入一条信息"></a>给集合中插入一条信息</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var t=new Pack(&#123;</span><br><span class="line">    name:<span class="string">&quot;a3&quot;</span>,</span><br><span class="line">    num:2,</span><br><span class="line">    items:[</span><br><span class="line">        &#123;name:<span class="string">&quot;b3&quot;</span>,num:1&#125;,</span><br><span class="line">        &#123;name:<span class="string">&quot;b4&quot;</span>,num:2&#125;,</span><br><span class="line">        &#123;name:<span class="string">&quot;b5&quot;</span>,num:3&#125;,</span><br><span class="line">        &#123;name:<span class="string">&quot;b6&quot;</span>,num:4&#125;,</span><br><span class="line">    ]&#125;);</span><br><span class="line">    t.save(&#123;&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">        console.log(data);</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>
<h3 id="同时插入多条数据"><a href="#同时插入多条数据" class="headerlink" title="同时插入多条数据"></a>同时插入多条数据</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">var arr = [</span><br><span class="line">    &#123;</span><br><span class="line">        name: <span class="string">&quot;a4&quot;</span>,</span><br><span class="line">        num: 3,</span><br><span class="line">        items: [</span><br><span class="line">            &#123; name: <span class="string">&quot;b4&quot;</span>, num: 1 &#125;,</span><br><span class="line">            &#123; name: <span class="string">&quot;b5&quot;</span>, num: 2 &#125;,</span><br><span class="line">            &#123; name: <span class="string">&quot;b6&quot;</span>, num: 3 &#125;,</span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        name: <span class="string">&quot;a5&quot;</span>,</span><br><span class="line">        num: 6,</span><br><span class="line">        items: [</span><br><span class="line">            &#123; name: <span class="string">&quot;b7&quot;</span>, num: 1 &#125;,</span><br><span class="line">            &#123; name: <span class="string">&quot;b5&quot;</span>, num: 2 &#125;,</span><br><span class="line">            &#123; name: <span class="string">&quot;b6&quot;</span>, num: 3 &#125;,</span><br><span class="line">        ]</span><br><span class="line">    &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">Pack.insertMany(arr,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="修改数据"><a href="#修改数据" class="headerlink" title="修改数据"></a>修改数据</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Pack.updateOne(&#123;name:<span class="string">&quot;a5&quot;</span>&#125;,&#123;<span class="variable">$set</span>:&#123;num:12&#125;&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">    Pack.find(&#123;&#125;,<span class="keyword">function</span>(error,data)&#123;</span><br><span class="line">        console.log(data);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Pack.deleteOne(&#123;name:<span class="string">&quot;a5&quot;</span>&#125;,<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">    Pack.find(&#123;&#125;,<span class="keyword">function</span>(error,data)&#123;</span><br><span class="line">        console.log(data);</span><br><span class="line">       &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="查找数据"><a href="#查找数据" class="headerlink" title="查找数据"></a>查找数据</h3><h4 id="查找所有"><a href="#查找所有" class="headerlink" title="查找所有"></a>查找所有</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Pack.find(&#123;&#125;,<span class="keyword">function</span>(error,data)&#123;</span><br><span class="line">        console.log(data);</span><br><span class="line"> &#125;)</span><br></pre></td></tr></table></figure>
<h4 id="查找某个"><a href="#查找某个" class="headerlink" title="查找某个"></a>查找某个</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Pack.find(&#123;name:<span class="string">&quot;a1&quot;</span>&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="查找条件"><a href="#查找条件" class="headerlink" title="查找条件"></a>查找条件</h4><p>$get:2  大于等于2的<br>$lte:2  小于等于2的</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Pack.find(&#123;num:&#123;<span class="variable">$gte</span>:2&#125;&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br><span class="line">Pack.find(&#123;num:&#123;<span class="variable">$lte</span>:2&#125;&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br><span class="line">//正则表达式判断</span><br><span class="line">Pack.find(&#123;name:/^\w\d$/&#125;,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/30/mongoDB/"><span>mongoDB</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/30/mongoDB/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-30T09:04:08.000Z">
          2021-01-30
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h3 id="MongoDB"><a href="#MongoDB" class="headerlink" title="MongoDB"></a>MongoDB</h3><p>MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。</p>
<p>MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的。</p>
<p>关系型数据库主要表现是二维表格，MongoDB是json存储方式</p>
<p>它的特点:高性能、易部署、易使用，存储数据非常方便。</p>
<img src="/ericxie-book/2021/01/30/mongoDB/table1.png" class="" title="url图片">
<img src="/ericxie-book/2021/01/30/mongoDB/table2.png" class="" title="url图片">
<p>一个mongodb中可以建立多个数据库。</p>
<p>MongoDB的默认数据库为”db”，该数据库存储在data目录中。</p>
<p>MongoDB的单个实例可以容纳多个独立的数据库，每一个都有自己的集合和权限，不同的数据库也放置在不同的文件中。</p>
<h3 id="MongoDB集合"><a href="#MongoDB集合" class="headerlink" title="MongoDB集合"></a>MongoDB集合</h3><p>集合就是 MongoDB 文档组，类似于 RDBMS （关系数据库管理系统：Relational Database Management System)中的表格。</p>
<p>集合存在于数据库中，集合没有固定的结构，这意味着你在对集合可以插入不同格式和类型的数据，但通常情况下我们插入集合的数据都会有一定的关联性。</p>
<h3 id="MongoDB-文档"><a href="#MongoDB-文档" class="headerlink" title="MongoDB 文档"></a>MongoDB 文档</h3><p>文档是一个键值(key-value)对(即BSON)。MongoDB 的文档不需要设置相同的字段，并且相同的字段不需要相同的数据类型，这与关系型数据库有很大的区别，也是 MongoDB 非常突出的特点。</p>
<p>一个简单的文档例子如下：<br>{“genres”: [“犯罪”,”剧情” ],”title”: “肖申克的救赎”}</p>
<img src="/ericxie-book/2021/01/30/mongoDB/table3.png" class="" title="url图片">

<h3 id="MongoDB安装"><a href="#MongoDB安装" class="headerlink" title="MongoDB安装"></a>MongoDB安装</h3><p><a target="_blank" rel="noopener" href="http://www.mongodb.org/downloads">下载</a></p>
<img src="/ericxie-book/2021/01/30/mongoDB/mongoDB1.png" class="" title="url图片">

<p>安装   创建数据目录：d:\data\db</p>
<img src="/ericxie-book/2021/01/30/mongoDB/mongoDB2.png" class="" title="url图片">

<p>命令行下运行MongoDB服务器</p>
<p>为了从命令提示符下运行MongoDB服务器，你必须从MongoDB目录的bin目录中执行mongod.exe文件。<br>或者将bin配置到环境变量path中。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; mongod --dbpath d:\data\db</span><br></pre></td></tr></table></figure>
<h3 id="进入mongodb命令行"><a href="#进入mongodb命令行" class="headerlink" title="进入mongodb命令行"></a>进入mongodb命令行</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo</span><br></pre></td></tr></table></figure>
<h3 id="数据库常用命令"><a href="#数据库常用命令" class="headerlink" title="数据库常用命令"></a>数据库常用命令</h3><h4 id="（1）Help查看命令提示"><a href="#（1）Help查看命令提示" class="headerlink" title="（1）Help查看命令提示"></a>（1）Help查看命令提示</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">help</span></span><br><span class="line">db.help()</span><br><span class="line">db.test.help()</span><br><span class="line">db.test.find().<span class="built_in">help</span>()</span><br></pre></td></tr></table></figure>
<h4 id="（2）创建-切换数据库"><a href="#（2）创建-切换数据库" class="headerlink" title="（2）创建/切换数据库"></a>（2）创建/切换数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">use music</span><br></pre></td></tr></table></figure>
<h4 id="（3）查询数据库"><a href="#（3）查询数据库" class="headerlink" title="（3）查询数据库"></a>（3）查询数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show dbs</span><br></pre></td></tr></table></figure>
<h4 id="（4）查看当前使用的数据库"><a href="#（4）查看当前使用的数据库" class="headerlink" title="（4）查看当前使用的数据库"></a>（4）查看当前使用的数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db/db.getName()</span><br></pre></td></tr></table></figure>
<h4 id="（5）显示当前DB状态"><a href="#（5）显示当前DB状态" class="headerlink" title="（5）显示当前DB状态"></a>（5）显示当前DB状态</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.stats()</span><br></pre></td></tr></table></figure>
<h4 id="（6）查看当前DB版本"><a href="#（6）查看当前DB版本" class="headerlink" title="（6）查看当前DB版本"></a>（6）查看当前DB版本</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.version()</span><br></pre></td></tr></table></figure>
<h4 id="（7）查看当前DB的链接机器地址"><a href="#（7）查看当前DB的链接机器地址" class="headerlink" title="（7）查看当前DB的链接机器地址"></a>（7）查看当前DB的链接机器地址</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.getMongo()</span><br></pre></td></tr></table></figure>
<h4 id="（8）删除数据库"><a href="#（8）删除数据库" class="headerlink" title="（8）删除数据库"></a>（8）删除数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.dropDatabase()</span><br></pre></td></tr></table></figure>
<h3 id="Collection集合操作"><a href="#Collection集合操作" class="headerlink" title="Collection集合操作"></a>Collection集合操作</h3><h4 id="（1）创建一个集合"><a href="#（1）创建一个集合" class="headerlink" title="（1）创建一个集合"></a>（1）创建一个集合</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.createCollection(<span class="string">&quot;collName&quot;</span>, &#123;size: 20, capped: <span class="literal">true</span>, max: 100&#125;);</span><br><span class="line">db.collName.isCapped(); //判断集合是否为定容量</span><br></pre></td></tr></table></figure>
<h4 id="（2）得到指定名称的集合"><a href="#（2）得到指定名称的集合" class="headerlink" title="（2）得到指定名称的集合"></a>（2）得到指定名称的集合</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.getCollection(<span class="string">&quot;account&quot;</span>);</span><br></pre></td></tr></table></figure>
<h4 id="（3）得到当前db的所有集合"><a href="#（3）得到当前db的所有集合" class="headerlink" title="（3）得到当前db的所有集合"></a>（3）得到当前db的所有集合</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.getCollectionNames();</span><br></pre></td></tr></table></figure>
<h4 id="（4）显示当前db所有集合的状态"><a href="#（4）显示当前db所有集合的状态" class="headerlink" title="（4）显示当前db所有集合的状态"></a>（4）显示当前db所有集合的状态</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.printCollectionStats();</span><br></pre></td></tr></table></figure>
<h3 id="添加、修改与删除集合数据"><a href="#添加、修改与删除集合数据" class="headerlink" title="添加、修改与删除集合数据"></a>添加、修改与删除集合数据</h3><h4 id="（1）添加"><a href="#（1）添加" class="headerlink" title="（1）添加"></a>（1）添加</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.users.save(&#123;name: <span class="string">&#x27;zhangsan&#x27;</span>, age: 25, sex: <span class="literal">true</span>&#125;);</span><br><span class="line"></span><br><span class="line">db.users.insert([&#123;name: <span class="string">&#x27;zhangsan&#x27;</span>, age: 25, sex: <span class="literal">true</span>&#125;,&#123;name: <span class="string">&#x27;lisi&#x27;</span>, age: 30, sex: <span class="literal">true</span>&#125;]);</span><br></pre></td></tr></table></figure>
<h4 id="（2）修改"><a href="#（2）修改" class="headerlink" title="（2）修改"></a>（2）修改</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">db.users.update(&#123;age: 25&#125;, &#123;<span class="variable">$set</span>: &#123;name: <span class="string">&#x27;changeName&#x27;</span>&#125;&#125;, <span class="literal">false</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">相当于：update users <span class="built_in">set</span> name = <span class="string">&#x27; changeName&#x27;</span> <span class="built_in">where</span> age = 25;</span><br><span class="line"></span><br><span class="line">db.users.update(&#123;name: <span class="string">&#x27;Lisi&#x27;</span>&#125;, &#123;<span class="variable">$inc</span>: &#123;age: 50&#125;&#125;, <span class="literal">false</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">相当于：update users <span class="built_in">set</span> age = age + 50 <span class="built_in">where</span> name = <span class="string">&#x27;Lisi&#x27;</span>;</span><br><span class="line"></span><br><span class="line">db.users.update(&#123;name: <span class="string">&#x27;Lisi&#x27;</span>&#125;, &#123;<span class="variable">$inc</span>: &#123;age: 50&#125;, <span class="variable">$set</span>: &#123;name: <span class="string">&#x27;hoho&#x27;</span>&#125;&#125;, <span class="literal">false</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">相当于：update users <span class="built_in">set</span> age = age + 50, name = <span class="string">&#x27;hoho&#x27;</span>  <span class="built_in">where</span> name = <span class="string">&#x27;Lisi&#x27;</span>;</span><br></pre></td></tr></table></figure>
<h4 id="（3）删除"><a href="#（3）删除" class="headerlink" title="（3）删除"></a>（3）删除</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.users.remove(&#123;age: 132&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="集合数据查询"><a href="#集合数据查询" class="headerlink" title="集合数据查询"></a>集合数据查询</h3><h4 id="（1）查询所有记录"><a href="#（1）查询所有记录" class="headerlink" title="（1）查询所有记录"></a>（1）查询所有记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find();</span><br><span class="line"></span><br><span class="line">相当于：select* from userInfo;</span><br></pre></td></tr></table></figure>
<h4 id="（2）查询去重后数据"><a href="#（2）查询去重后数据" class="headerlink" title="（2）查询去重后数据"></a>（2）查询去重后数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.distinct(<span class="string">&quot;name&quot;</span>);</span><br><span class="line"></span><br><span class="line">相当于：select distict name from userInfo;</span><br></pre></td></tr></table></figure>
<h4 id="（3）查询age-22的记录"><a href="#（3）查询age-22的记录" class="headerlink" title="（3）查询age = 22的记录"></a>（3）查询age = 22的记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;<span class="string">&quot;age&quot;</span>: 22&#125;);</span><br><span class="line"></span><br><span class="line">相当于： select * from userInfo <span class="built_in">where</span> age = 22;</span><br></pre></td></tr></table></figure>
<h4 id="（4）查询age-gt-22的记录"><a href="#（4）查询age-gt-22的记录" class="headerlink" title="（4）查询age &gt; 22的记录"></a>（4）查询age &gt; 22的记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$gt</span>: 22&#125;&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> age &gt; 22;</span><br></pre></td></tr></table></figure>
<h4 id="（5）查询age-lt-22的记录"><a href="#（5）查询age-lt-22的记录" class="headerlink" title="（5）查询age &lt; 22的记录"></a>（5）查询age &lt; 22的记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$lt</span>: 22&#125;&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> age &lt; 22;</span><br></pre></td></tr></table></figure>
<h4 id="（6）查询age-gt-25的记录"><a href="#（6）查询age-gt-25的记录" class="headerlink" title="（6）查询age &gt;= 25的记录"></a>（6）查询age &gt;= 25的记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$gte</span>: 25&#125;&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> age &gt;= 25;</span><br></pre></td></tr></table></figure>
<h4 id="（7）查询age-lt-25的记录"><a href="#（7）查询age-lt-25的记录" class="headerlink" title="（7）查询age &lt;= 25的记录"></a>（7）查询age &lt;= 25的记录</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$lte</span>: 25&#125;&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="（8）查询age-gt-23-并且-age-lt-26"><a href="#（8）查询age-gt-23-并且-age-lt-26" class="headerlink" title="（8）查询age &gt;= 23 并且 age &lt;= 26"></a>（8）查询age &gt;= 23 并且 age &lt;= 26</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$gte</span>: 23, <span class="variable">$lte</span>: 26&#125;&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="（9）查询name中包含-mongo的数据"><a href="#（9）查询name中包含-mongo的数据" class="headerlink" title="（9）查询name中包含 mongo的数据"></a>（9）查询name中包含 mongo的数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;name: /mongo/&#125;);</span><br><span class="line"></span><br><span class="line">//相当于%%</span><br><span class="line"></span><br><span class="line">select * from userInfo <span class="built_in">where</span> name like <span class="string">&#x27;%mongo%&#x27;</span>;</span><br></pre></td></tr></table></figure>
<h4 id="（10）查询name中以mongo开头的"><a href="#（10）查询name中以mongo开头的" class="headerlink" title="（10）查询name中以mongo开头的"></a>（10）查询name中以mongo开头的</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;name: /^mongo/&#125;);</span><br><span class="line"></span><br><span class="line">相当于： select * from userInfo <span class="built_in">where</span> name like <span class="string">&#x27;mongo%&#x27;</span>;</span><br></pre></td></tr></table></figure>
<h4 id="（11）查询指定列name、age数据"><a href="#（11）查询指定列name、age数据" class="headerlink" title="（11）查询指定列name、age数据"></a>（11）查询指定列name、age数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;&#125;, &#123;name: 1, age: 1&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select name, age from userInfo;</span><br></pre></td></tr></table></figure>
<h4 id="（12）查询指定列name、age数据-age-gt-25"><a href="#（12）查询指定列name、age数据-age-gt-25" class="headerlink" title="（12）查询指定列name、age数据, age &gt; 25"></a>（12）查询指定列name、age数据, age &gt; 25</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$gt</span>: 25&#125;&#125;, &#123;name: 1, age: 1&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select name, age from userInfo <span class="built_in">where</span> age &gt;25;</span><br></pre></td></tr></table></figure>
<h4 id="（13）按照年龄排序"><a href="#（13）按照年龄排序" class="headerlink" title="（13）按照年龄排序"></a>（13）按照年龄排序</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">升序：db.userInfo.find().sort(&#123;age: 1&#125;);</span><br><span class="line"></span><br><span class="line">降序：db.userInfo.find().sort(&#123;age: -1&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="（14）查询name-zhangsan-age-22的数据"><a href="#（14）查询name-zhangsan-age-22的数据" class="headerlink" title="（14）查询name = zhangsan, age = 22的数据"></a>（14）查询name = zhangsan, age = 22的数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;name: <span class="string">&#x27;zhangsan&#x27;</span>, age: 22&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> name = <span class="string">&#x27;zhangsan&#x27;</span> and age = ’22<span class="string">&#x27;;</span></span><br></pre></td></tr></table></figure>
<h4 id="（15）查询前5条数据"><a href="#（15）查询前5条数据" class="headerlink" title="（15）查询前5条数据"></a>（15）查询前5条数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find().<span class="built_in">limit</span>(5);</span><br><span class="line"></span><br><span class="line">相当于：select top 5 * from userInfo;</span><br></pre></td></tr></table></figure>
<h4 id="（16）查询10条以后的数据"><a href="#（16）查询10条以后的数据" class="headerlink" title="（16）查询10条以后的数据"></a>（16）查询10条以后的数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find().skip(10);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> id not <span class="keyword">in</span> (select top 10 * from userInfo);</span><br></pre></td></tr></table></figure>
<h4 id="（17）查询在5-10之间的数据"><a href="#（17）查询在5-10之间的数据" class="headerlink" title="（17）查询在5-10之间的数据"></a>（17）查询在5-10之间的数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find().<span class="built_in">limit</span>(10).skip(5);</span><br></pre></td></tr></table></figure>
<h4 id="（18）or与-查询"><a href="#（18）or与-查询" class="headerlink" title="（18）or与 查询"></a>（18）or与 查询</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;<span class="variable">$or</span>: [&#123;age: 22&#125;, &#123;age: 25&#125;]&#125;);</span><br><span class="line"></span><br><span class="line">相当于：select * from userInfo <span class="built_in">where</span> age = 22 or age = 25;</span><br></pre></td></tr></table></figure>
<h4 id="（19）查询第一条数据"><a href="#（19）查询第一条数据" class="headerlink" title="（19）查询第一条数据"></a>（19）查询第一条数据</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.findOne();</span><br><span class="line"></span><br><span class="line">相当于：select top 1 * from userInfo;db.userInfo.find().<span class="built_in">limit</span>(1);</span><br></pre></td></tr></table></figure>
<h4 id="（20）查询某个结果集的记录条数"><a href="#（20）查询某个结果集的记录条数" class="headerlink" title="（20）查询某个结果集的记录条数"></a>（20）查询某个结果集的记录条数</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.userInfo.find(&#123;age: &#123;<span class="variable">$gte</span>: 25&#125;&#125;).count();</span><br><span class="line"></span><br><span class="line">相当于：select count(*) from userInfo <span class="built_in">where</span> age &gt;= 20;</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/30/art-template/"><span>art-template</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/30/art-template/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-30T03:09:47.000Z">
          2021-01-30
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="页面渲染模式"><a href="#页面渲染模式" class="headerlink" title="页面渲染模式"></a>页面渲染模式</h2><h3 id="SSR"><a href="#SSR" class="headerlink" title="SSR"></a>SSR</h3><p>(Server Side Rendering) ：传统的渲染方式，由服务端把渲染的完整的页面吐给客户端。这样减少了一次客户端到服务端的一次http请求，加快相应速度，一般用于首屏的性能优化。</p>
<h4 id="SSR优点"><a href="#SSR优点" class="headerlink" title="SSR优点"></a>SSR优点</h4><p>例如SEO–因为访问一个请求，返回的就是页面全部的HTML结构，包含所需要呈现的所有数据，于是例如搜索引擎或者爬虫的数据抓取；</p>
<p>目前使用MV*架构的项目，大都是前后端分离，数据都是动态生成，不利于SEO优化<br>利于首屏渲染性能高–首屏的页面加载来自于服务器，不依赖与服务端的接口请求再数据处理；</p>
<h4 id="SSR缺点"><a href="#SSR缺点" class="headerlink" title="SSR缺点"></a>SSR缺点</h4><p>性能全都依赖于服务器<br>前端界面开发可操作性不高</p>
<h3 id="CSR"><a href="#CSR" class="headerlink" title="CSR"></a>CSR</h3><p>CSR(Client Side Rendering)：是一种目前流行的渲染方式，它依赖的是运行在客户端的JS，用户首次发送请求只能得到小部分的指引性HTML代码。第二次请求将会请求更多包含HTML字符串的JS文件。</p>
<h4 id="CSR优点"><a href="#CSR优点" class="headerlink" title="CSR优点"></a>CSR优点</h4><p>FP最快<br>客户端体验较好，因为在数据没更新之前，页面框架和元素是可以在dom生成的</p>
<p>FP：仅有一个 div 根节点。以VUE为例，div#app 注册一个空的div<br>FCP：包含页面的基本框架，但没有数据内容。以VUE为例，每个template中的div框架，对应VUE生命周期的mounted<br>FMP：包含页面所有元素及数据。以VUE为例，通过接口更新到页面的数据后完整的页面展示；对应VUE的生命周期中的updated</p>
<p>简而言之，就是数据拼接HTML字符串这件事放在服务端还是客户端造成了两者区别。</p>
<h4 id="CSR缺点"><a href="#CSR缺点" class="headerlink" title="CSR缺点"></a>CSR缺点</h4><p>不利于SEO–爬虫数据不好爬呀~~<br>整体加载完速度慢</p>
<h3 id="两者有何不同"><a href="#两者有何不同" class="headerlink" title="两者有何不同"></a>两者有何不同</h3><p>服务器端渲染的优势在于首屏渲染速度块，简单来讲它不需要来回多次往返于客户端和服务端。但是其性能等众多因素会影响用户体验，比如说：网速，在线活跃人数，服务器的物理位置等等。而客户端渲染则和服务端渲染相反，因为多次和服务器的交互导致首屏加载速度慢。但一旦这些请求完成之后，用户和页面之间的交互时用户体验就会好很多。</p>
<p>用一个现实生活的例子来看：假如从超市买东西吃，以SSR的角度来看，你每次在超市买完随即吃完再走，每次饿了都需要出发去超市。而从CSR的角度来看，就是你从超市购买许多原材料再拿回家去自己煮，多了能放冰箱，这样每次肚子饿了就不需要每次都往超市跑，唯一麻烦一点在于你得花时间挑选食材。</p>
<h3 id="优化方案"><a href="#优化方案" class="headerlink" title="优化方案"></a>优化方案</h3><p>1、优化首屏加载，减少白屏时间，提升加载性能：<br>2、加速或减少HTTP请求损耗：使用CDN加载公用库，使用强缓存和协商缓存，使用域名收敛，小图片使用Base64代替，使用Get请求代替Post请求，设置 Access-Control-Max-Age 减少预检请求，页面内跳转其他域名或请求其他域名的资源时使用浏览器prefetch预解析等；<br>3、延迟加载：非重要的库、非首屏图片延迟加载，SPA的组件懒加载等；<br>4、减少请求内容的体积：开启服务器Gzip压缩，JS、CSS文件压缩合并，减少cookies大小，SSR直接输出渲染后的HTML等；<br>5、浏览器渲染原理：优化关键渲染路径，尽可能减少阻塞渲染的JS、CSS；<br>6、优化用户等待体验：白屏使用加载进度条、loading图、骨架屏代替等；</p>
<p>强缓存和协商缓存</p>
<p>强缓存是利用http头中的Expires和Cache-Control两个字段来控制的，用来表示资源的缓存时间<br>协商缓存：浏览器第一次请求一个资源的时候，服务器返回的header中会加上Last-Modify，Last-modify是一个时间标识该资源的最后修改时间；当浏览器再次请求该资源时，request的请求头中会包含If-Modify-Since，该值为缓存之前返回的Last-Modify。服务器收到If-Modify-Since后，根据资源的最后修改时间判断是否命中缓存；其中Etag：web服务器响应请求时，告诉浏览器当前资源在服务器的唯一标识</p>
<p>Access-Control-Max-Age：缓存可以被缓存的时间</p>
<p>SPA 只有一张Web页面的应用,是加载单个HTML页面并在用户与应用程序交互时动态更新该页面的Web应用程序，是指在浏览器中运行的应用，在使用期间不会重新加载页面。像所有的应用一样，它旨在帮助用户完成任务，比如“编写文档”或者“管理Web服务器”</p>
<p>域名发散<br>域名发散就是为了突破浏览器对于同一域名并发请求数的限制，使用域名发散为同一个服务申请多个域名，从而可以一定程度上提高并发量；当然，由于建立新的请求需要一定的代价，因此需要在域名发散与域名收敛间进行trade off，通常发散的域名个数为2-4个；</p>
<p>域名收敛<br>域名收敛就是将静态资源放在一个域名下不进行发散，这主要是为了适应移动端的发展需求；通常DNS是一个开销较大的操作，而移动端由于网络带宽和实时性、资源等的限制，这些开销对移动端的用户体验是致命的，因此需要进行域名收敛；</p>
<p>域名发散是pc端为了利用浏览器的多线程并行下载能力。而域名收敛多用与移动端，提高性能，因为dns解析是是从后向前迭代解析，如果域名过多性能会下降，增加DNS的解析开销。</p>
<p>DNS 预解析：浏览器会在加载网页时对网页中的域名进行解析缓存，这样在你单击当前网页中的连接时就无需进行DNS的解析，减少用户等待时间，提高用户体验。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;link rel=<span class="string">&quot;dns-prefetch&quot;</span> href=<span class="string">&quot;www.ytuwlg.iteye.com&quot;</span> /&gt;</span><br></pre></td></tr></table></figure>
<p>Gzip页面压缩，像服务器发送压缩文件，同时服务器需要设置解析</p>
<h4 id="简而言之，SSR强在首屏渲染。而CSR强在用户和页面多交互的场景"><a href="#简而言之，SSR强在首屏渲染。而CSR强在用户和页面多交互的场景" class="headerlink" title="简而言之，SSR强在首屏渲染。而CSR强在用户和页面多交互的场景"></a>简而言之，SSR强在首屏渲染。而CSR强在用户和页面多交互的场景</h4><h2 id="art介绍"><a href="#art介绍" class="headerlink" title="art介绍"></a>art介绍</h2><p>art-template 是一个简约、超快的模板引擎。<br>它采用作用域预声明的技术来优化模板渲染速度，从而获得接近 JavaScript 极限的运行性能，并且同时支持 NodeJS 和浏览器。</p>
<p>art-template 既可以用在前端，也可以用在后端<br>当CSR时前端直接使用art-template根据通信的数据渲染页面<br>当SSR时node也可以渲染生成静态页面或者将静态页面直接发回给前端</p>
<h3 id="CSR时前端通过art渲染页面"><a href="#CSR时前端通过art渲染页面" class="headerlink" title="CSR时前端通过art渲染页面"></a>CSR时前端通过art渲染页面</h3><h4 id="下载安装"><a href="#下载安装" class="headerlink" title="下载安装"></a>下载安装</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i art-template -S</span><br></pre></td></tr></table></figure>
<h4 id="引入和基础使用"><a href="#引入和基础使用" class="headerlink" title="引入和基础使用"></a>引入和基础使用</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">    &lt;script src=<span class="string">&quot;./node_modules/art-template/lib/template-web.js&quot;</span>&gt;&lt;/script&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div id=<span class="string">&quot;app&quot;</span>&gt;&lt;/div&gt;</span><br><span class="line">    &lt;script id=<span class="string">&quot;tp&quot;</span> <span class="built_in">type</span>=<span class="string">&quot;text/html&quot;</span>&gt;</span><br><span class="line">        &#123;&#123;<span class="keyword">if</span> user&#125;&#125;</span><br><span class="line">        &lt;h2&gt;&#123;&#123;user.name&#125;&#125;&lt;/h2&gt;</span><br><span class="line">        &lt;h2&gt;&#123;&#123;user.age&#125;&#125;&lt;/h2&gt;</span><br><span class="line">        &#123;&#123;/<span class="keyword">if</span>&#125;&#125;</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var user=&#123;name:<span class="string">&quot;xietian&quot;</span>,age:30&#125;;</span><br><span class="line">        document.querySelector(<span class="string">&quot;#app&quot;</span>).innerHTML=template(<span class="string">&quot;tp&quot;</span>,&#123;user:user&#125;);</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<h4 id="语法使用"><a href="#语法使用" class="headerlink" title="语法使用"></a>语法使用</h4><p>art分为两种语法，标准语法与原始语法。标准语法可以让模板易读写，而原始语法拥有强大的逻辑表达能力。</p>
<h5 id="输出"><a href="#输出" class="headerlink" title="输出"></a>输出</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;value&#125;&#125;</span><br><span class="line">&#123;&#123;data.key&#125;&#125;</span><br><span class="line">&#123;&#123;data[<span class="string">&#x27;key&#x27;</span>]&#125;&#125;</span><br><span class="line">&#123;&#123;a ? b : c&#125;&#125;</span><br><span class="line">&#123;&#123;a || b&#125;&#125;</span><br><span class="line">&#123;&#123;a + b&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;%= value %&gt;</span><br><span class="line">&lt;%= data.key %&gt;</span><br><span class="line">&lt;%= data[<span class="string">&#x27;key&#x27;</span>] %&gt;</span><br><span class="line">&lt;%= a ? b : c %&gt;</span><br><span class="line">&lt;%= a || b %&gt;</span><br><span class="line">&lt;%= a + b %&gt;</span><br></pre></td></tr></table></figure>
<p>模板一级特殊变量</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;%= <span class="variable">$data</span> %&gt;</span><br></pre></td></tr></table></figure>
<h5 id="原文输出"><a href="#原文输出" class="headerlink" title="原文输出"></a>原文输出</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;@ value &#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;%- value %&gt;</span><br></pre></td></tr></table></figure>
<p>原文输出语句不会对 HTML 内容进行转义处理，可能存在安全风险，请谨慎使用。</p>
<h5 id="条件"><a href="#条件" class="headerlink" title="条件"></a>条件</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;<span class="keyword">if</span> value&#125;&#125; ... &#123;&#123;/<span class="keyword">if</span>&#125;&#125;</span><br><span class="line">&#123;&#123;<span class="keyword">if</span> v1&#125;&#125; ... &#123;&#123;<span class="keyword">else</span> <span class="keyword">if</span> v2&#125;&#125; ... &#123;&#123;/<span class="keyword">if</span>&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;% <span class="keyword">if</span> (value) &#123; %&gt; ... &lt;% &#125; %&gt;</span><br><span class="line">&lt;% <span class="keyword">if</span> (v1) &#123; %&gt; ... &lt;% &#125; <span class="keyword">else</span> <span class="keyword">if</span> (v2) &#123; %&gt; ... &lt;% &#125; %&gt;</span><br></pre></td></tr></table></figure>
<h5 id="循环"><a href="#循环" class="headerlink" title="循环"></a>循环</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;each target&#125;&#125;</span><br><span class="line">    &#123;&#123;<span class="variable">$index</span>&#125;&#125; &#123;&#123;<span class="variable">$value</span>&#125;&#125;</span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;% <span class="keyword">for</span>(var i = 0; i &lt; target.length; i++)&#123; %&gt;</span><br><span class="line">    &lt;%= i %&gt; &lt;%= target[i] %&gt;</span><br><span class="line">&lt;% &#125; %&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">target 支持 array 与 object 的迭代，其默认值为 <span class="variable">$data</span>。</span><br><span class="line"><span class="variable">$value</span> 与 <span class="variable">$index</span> 可以自定义：&#123;&#123;each target <span class="variable">$val</span> <span class="variable">$key</span>&#125;&#125;。</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> &#123;&#123;each user <span class="variable">$key</span> <span class="variable">$val</span>&#125;&#125;</span><br><span class="line">    &lt;div&gt;&#123;&#123;<span class="variable">$key</span>&#125;&#125;:&#123;&#123;<span class="variable">$val</span>&#125;&#125;&lt;/div&gt;</span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>
<h5 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;<span class="built_in">set</span> temp = data.sub.content&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;% var temp = data.sub.content; %&gt;</span><br></pre></td></tr></table></figure>
<h3 id="SSR时Node中express通过art渲染页面"><a href="#SSR时Node中express通过art渲染页面" class="headerlink" title="SSR时Node中express通过art渲染页面"></a>SSR时Node中express通过art渲染页面</h3><h4 id="下载安装引入"><a href="#下载安装引入" class="headerlink" title="下载安装引入"></a>下载安装引入</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i express express-art-template -S</span><br></pre></td></tr></table></figure>
<h4 id="express中语法使用"><a href="#express中语法使用" class="headerlink" title="express中语法使用"></a>express中语法使用</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">const express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(express.static(<span class="string">&quot;./&quot;</span>));//设置静态目录的</span><br><span class="line">app.engine(<span class="string">&#x27;art&#x27;</span>, require(<span class="string">&#x27;express-art-template&#x27;</span>));</span><br><span class="line"></span><br><span class="line">app.set(<span class="string">&quot;views options&quot;</span>,&#123;</span><br><span class="line">    debug:process.env.Node_ENV!==<span class="string">&#x27;production&#x27;</span></span><br><span class="line">&#125;);//// 启动模板引擎调试模式。如果为 <span class="literal">true</span>: &#123;cache:<span class="literal">false</span>, minimize:<span class="literal">false</span>, compileDebug:<span class="literal">true</span>&#125; </span><br><span class="line">cache 是否开启缓存 </span><br><span class="line">minimize 是否开启压缩。它会运行 htmlMinifier，将页面 HTML、CSS、CSS 进行压缩输出</span><br><span class="line">compileDebug 是否编译调试版</span><br><span class="line"></span><br><span class="line">compileDebug:<span class="literal">true</span>&#125;</span><br><span class="line">//默认文件夹是根目录，这里指定为view文件夹</span><br><span class="line">app.set(<span class="string">&quot;views&quot;</span>,path.join(__dirname,<span class="string">&quot;./view&quot;</span>));//设置views目录为view文件夹</span><br><span class="line">app.set(<span class="string">&quot;view engine&quot;</span>,<span class="string">&quot;art&quot;</span>);//设置view内容默认为art文件，渲染时可以不加扩展名</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.render(<span class="string">&quot;index.art&quot;</span>,&#123;data&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">//app.set(<span class="string">&quot;view engine&quot;</span>,<span class="string">&quot;art&quot;</span>);  这个设置后就可以不用写扩展名</span><br><span class="line">app.get(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.render(<span class="string">&quot;index&quot;</span>,&#123;data&#125;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>基础语法与上面相同</p>
<h5 id="模板继承"><a href="#模板继承" class="headerlink" title="模板继承"></a>模板继承</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;extend <span class="string">&#x27;./layout.art&#x27;</span>&#125;&#125;</span><br><span class="line">&#123;&#123;block <span class="string">&#x27;head&#x27;</span>&#125;&#125; ... &#123;&#123;/block&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;% extend(<span class="string">&#x27;./layout.art&#x27;</span>) %&gt;</span><br><span class="line">&lt;% block(<span class="string">&#x27;head&#x27;</span>, <span class="function"><span class="title">function</span></span>()&#123; %&gt; ... &lt;% &#125;) %&gt;</span><br></pre></td></tr></table></figure>
<p>模板继承允许你构建一个包含你站点共同元素的基本模板“骨架”。范例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--layout.art--&gt;</span><br><span class="line">&lt;!doctype html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;utf-8&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;&#123;&#123;block <span class="string">&#x27;title&#x27;</span>&#125;&#125;My Site&#123;&#123;/block&#125;&#125;&lt;/title&gt;</span><br><span class="line"></span><br><span class="line">    &#123;&#123;block <span class="string">&#x27;head&#x27;</span>&#125;&#125;</span><br><span class="line">    &lt;link rel=<span class="string">&quot;stylesheet&quot;</span> href=<span class="string">&quot;main.css&quot;</span>&gt;</span><br><span class="line">    &#123;&#123;/block&#125;&#125;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &#123;&#123;block <span class="string">&#x27;content&#x27;</span>&#125;&#125;&#123;&#123;/block&#125;&#125;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&lt;!--index.art--&gt;</span><br><span class="line">&#123;&#123;extend <span class="string">&#x27;./layout.art&#x27;</span>&#125;&#125;</span><br><span class="line"></span><br><span class="line">&#123;&#123;block <span class="string">&#x27;title&#x27;</span>&#125;&#125;&#123;&#123;title&#125;&#125;&#123;&#123;/block&#125;&#125;</span><br><span class="line"></span><br><span class="line">&#123;&#123;block <span class="string">&#x27;head&#x27;</span>&#125;&#125;</span><br><span class="line">    &lt;link rel=<span class="string">&quot;stylesheet&quot;</span> href=<span class="string">&quot;custom.css&quot;</span>&gt;</span><br><span class="line">&#123;&#123;/block&#125;&#125;</span><br><span class="line"></span><br><span class="line">&#123;&#123;block <span class="string">&#x27;content&#x27;</span>&#125;&#125;</span><br><span class="line">&lt;p&gt;This is just an awesome page.&lt;/p&gt;</span><br><span class="line">&#123;&#123;/block&#125;&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(express.static(<span class="string">&quot;./&quot;</span>));</span><br><span class="line">app.engine(<span class="string">&#x27;art&#x27;</span>, require(<span class="string">&#x27;express-art-template&#x27;</span>));</span><br><span class="line">app.get(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">   res.render(<span class="string">&quot;./index.art&quot;</span>,&#123;title:<span class="string">&quot;xietian&quot;</span>&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>渲染 index.art 后，将自动应用布局骨架。</p>
<h5 id="子模板"><a href="#子模板" class="headerlink" title="子模板"></a>子模板</h5><p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;include <span class="string">&#x27;./header.art&#x27;</span>&#125;&#125;</span><br><span class="line">&#123;&#123;include <span class="string">&#x27;./header.art&#x27;</span> data&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;% include(<span class="string">&#x27;./header.art&#x27;</span>) %&gt;</span><br><span class="line">&lt;% include(<span class="string">&#x27;./header.art&#x27;</span>, data) %&gt;</span><br></pre></td></tr></table></figure>
<p>data 数默认值为 $data；标准语法不支持声明 object 与 array，只支持引用变量，而原始语法不受限制。<br>art-template 内建 HTML 压缩器，请避免书写 HTML 非正常闭合的子模板，否则开启压缩后标签可能会被意外“优化。</p>
<h5 id="过滤器"><a href="#过滤器" class="headerlink" title="过滤器"></a>过滤器</h5><p>注册过滤器</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var template=require(<span class="string">&quot;art-template&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(express.static(<span class="string">&quot;./&quot;</span>));</span><br><span class="line">app.engine(<span class="string">&#x27;art&#x27;</span>, require(<span class="string">&#x27;express-art-template&#x27;</span>));</span><br><span class="line">template.defaults.imports.randomColor=<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">   var col=<span class="string">&quot;#&quot;</span>;</span><br><span class="line">   <span class="keyword">for</span>(var i=0;i&lt;6;i++)&#123;</span><br><span class="line">      col+=Math.floor(Math.random()*16).toString(16);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="built_in">return</span> col;</span><br><span class="line">&#125;</span><br><span class="line">template.defaults.imports.getSum=<span class="keyword">function</span>(a,b)&#123;</span><br><span class="line">  <span class="built_in">return</span> a+b;</span><br><span class="line">&#125;</span><br><span class="line">app.get(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">   res.render(<span class="string">&quot;./c.art&quot;</span>,&#123;data:<span class="string">&quot;xietian&quot;</span>&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>过滤器函数第一个参数接受目标值。</p>
<p>标准语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;extend <span class="string">&#x27;./layout.art&#x27;</span>&#125;&#125;</span><br><span class="line">&#123;&#123;block <span class="string">&#x27;title&#x27;</span>&#125;&#125;&#123;&#123;data&#125;&#125; site&#123;&#123;/block&#125;&#125;</span><br><span class="line"> &#123;&#123;block <span class="string">&#x27;head&#x27;</span>&#125;&#125;</span><br><span class="line">    &lt;link rel=<span class="string">&quot;stylesheet&quot;</span> href=<span class="string">&quot;./views/b.css&quot;</span>&gt;</span><br><span class="line">&#123;&#123;/block&#125;&#125;</span><br><span class="line">&#123;&#123;block <span class="string">&#x27;content&#x27;</span>&#125;&#125;</span><br><span class="line"></span><br><span class="line">&lt;div style=<span class="string">&#x27;color:&#123;&#123;randomColor&#125;&#125;&#x27;</span>&#125;&gt;asdb&lt;/div&gt;</span><br><span class="line">&lt;div&gt;&#123;&#123;getSum(5,6)&#125;&#125;&lt;/div&gt;</span><br><span class="line">&#123;&#123;/block&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>原始语法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;%= <span class="variable">$imports</span>.dateFormat(<span class="variable">$imports</span>.getSum(5,6), <span class="string">&#x27;&#x27;</span>) %&gt;</span><br></pre></td></tr></table></figure>
<h3 id="根据数据生成静态页面"><a href="#根据数据生成静态页面" class="headerlink" title="根据数据生成静态页面"></a>根据数据生成静态页面</h3><p>CMS网站发布系统的原型</p>
<p>a.art</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;&#123;&#123;block <span class="string">&#x27;title&#x27;</span>&#125;&#125;my site&#123;&#123;/block&#125;&#125;&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;h1&gt;&#123;&#123;title&#125;&#125;&lt;/h1&gt;</span><br><span class="line">    &lt;img src=<span class="string">&#x27;&#123;&#123;imgSrc&#125;&#125;&#x27;</span>&gt;</span><br><span class="line">    &lt;div style=<span class="string">&#x27;color:&#123;&#123;randomColor&#125;&#125;&#x27;</span>&gt;</span><br><span class="line">        &#123;&#123;content&#125;&#125;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">    &lt;ul&gt;</span><br><span class="line">        &#123;&#123;each list&#125;&#125;</span><br><span class="line">        &lt;li&gt;&#123;&#123;<span class="variable">$value</span>&#125;&#125;&lt;/li&gt;</span><br><span class="line">        &#123;&#123;/each&#125;&#125;</span><br><span class="line">    &lt;/ul&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;html&gt;</span><br></pre></td></tr></table></figure>
<p>index.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var path=require(<span class="string">&quot;path&quot;</span>);</span><br><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">var template=require(<span class="string">&quot;art-template&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(express.static(<span class="string">&quot;./&quot;</span>));</span><br><span class="line">app.engine(<span class="string">&#x27;art&#x27;</span>, require(<span class="string">&#x27;express-art-template&#x27;</span>));</span><br><span class="line">app.listen(4001);</span><br><span class="line"></span><br><span class="line">template.defaults.imports.randomColor=<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">   var col=<span class="string">&quot;#&quot;</span>;</span><br><span class="line">   <span class="keyword">for</span>(var i=0;i&lt;6;i++)&#123;</span><br><span class="line">      col+=Math.floor(Math.random()*16).toString(16);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="built_in">return</span> col;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var arr=[</span><br><span class="line">   &#123;title:<span class="string">&quot;第一页&quot;</span>,imgSrc:<span class="string">&quot;./2.jpg&quot;</span>,content:<span class="string">&quot;这篇文章的内容是1...&quot;</span>,list:[1,2,3,4,5]&#125;,</span><br><span class="line">   &#123;title:<span class="string">&quot;第二页&quot;</span>,imgSrc:<span class="string">&quot;./3.jpg&quot;</span>,content:<span class="string">&quot;这篇文章的内容是2...&quot;</span>,list:[6,7,8,9]&#125;,</span><br><span class="line">   &#123;title:<span class="string">&quot;第三页&quot;</span>,imgSrc:<span class="string">&quot;./4.jpg&quot;</span>,content:<span class="string">&quot;这篇文章的内容是3...&quot;</span>,list:[1,2,45,2]&#125;,</span><br><span class="line">   &#123;title:<span class="string">&quot;第四页&quot;</span>,imgSrc:<span class="string">&quot;./5.jpg&quot;</span>,content:<span class="string">&quot;这篇文章的内容是4...&quot;</span>,list:[23,5,24,5]&#125;,</span><br><span class="line">   &#123;title:<span class="string">&quot;第五页&quot;</span>,imgSrc:<span class="string">&quot;./6.jpg&quot;</span>,content:<span class="string">&quot;这篇文章的内容是5...&quot;</span>,list:[2,4,5,21]&#125;,</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> saveFile(html,i)&#123;</span><br><span class="line">   <span class="built_in">return</span> new Promise(resolve=&gt;&#123;</span><br><span class="line">      fs.writeFile(path.join(__dirname,<span class="string">&quot;./public/&quot;</span>+i+<span class="string">&quot;.html&quot;</span>),html,<span class="string">&quot;utf8&quot;</span>,<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">         resolve();</span><br><span class="line">      &#125;)</span><br><span class="line">   &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">async <span class="keyword">function</span> <span class="function"><span class="title">init</span></span>()&#123;</span><br><span class="line">   <span class="keyword">for</span>(var i=0;i&lt;arr.length;i++)&#123;</span><br><span class="line">     await saveFile(template(path.join(__dirname,<span class="string">&#x27;./views/a.art&#x27;</span>),arr[i]),i)</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">init();</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/27/express-router/"><span>express-router</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/27/express-router/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-27T12:02:20.000Z">
          2021-01-27
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="express中间件和路由"><a href="#express中间件和路由" class="headerlink" title="express中间件和路由"></a>express中间件和路由</h2><h3 id="express中的路由"><a href="#express中的路由" class="headerlink" title="express中的路由"></a>express中的路由</h3><p>下面的方法可以创建路由</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">const express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">const router=express.Router();</span><br></pre></td></tr></table></figure>
<h4 id="路由的处理"><a href="#路由的处理" class="headerlink" title="路由的处理"></a>路由的处理</h4><p>router.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">const express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">//路由中间件</span><br><span class="line">const router=express.Router();</span><br><span class="line"></span><br><span class="line">router.get(<span class="string">&quot;/index&quot;</span>,(req,res,next)=&gt;&#123;</span><br><span class="line">    res.json(req.query)</span><br><span class="line">&#125;);</span><br><span class="line">router.post(<span class="string">&quot;/index&quot;</span>,(req,res,next)=&gt;&#123;</span><br><span class="line">    const data=req.body;</span><br><span class="line">    res.send(data);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.get(<span class="string">&quot;/api&quot;</span>,(req,res,next)=&gt;&#123;</span><br><span class="line">    res.send(<span class="string">&quot;api page&quot;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">router.put(<span class="string">&quot;/index&quot;</span>,(req,res,next)=&gt;&#123;</span><br><span class="line">    const data=req.body;</span><br><span class="line">    res.send(data);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">module.exports=router;</span><br><span class="line">//最下面的这里需要导出这个路由</span><br></pre></td></tr></table></figure>
<p>server.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">const express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">const router=require(<span class="string">&quot;./router&quot;</span>);</span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,router);</span><br></pre></td></tr></table></figure>
<p>当执行后，前端访问服务器时，会自动被路由router分配到不同的内容中进行处理</p>
<h3 id="express中间件"><a href="#express中间件" class="headerlink" title="express中间件"></a>express中间件</h3><p>在express中间件分为5种:1、自定义中间件，2、路由中间件，3、静态中间件，4、第三方中间件，5、错误处理中间件</p>
<h4 id="自定义中间件"><a href="#自定义中间件" class="headerlink" title="自定义中间件"></a>自定义中间件</h4><p>下面案例中use就是中间件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    console.log(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;b&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.jsonp(&#123;a:1,b:2&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>也可以这么写</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    console.log(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;b&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;c&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.jsonp(&#123;a:1,b:2&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>还可以这么写</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">var listHandler=[<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    console.log(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;b&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;c&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;]</span><br><span class="line">app.use(<span class="string">&quot;/a&quot;</span>,listHandler)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.jsonp(&#123;a:1,b:2&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>也可以通过引入的方式使用</p>
<p>list.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">const list=(req,res,next)=&gt;&#123;</span><br><span class="line">    <span class="built_in">let</span> data=Array(100).fill(1).map((item,index)=&gt;index+1)</span><br><span class="line">    res.send(data);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">exports.list=list;</span><br></pre></td></tr></table></figure>
<p>server.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">var &#123;list&#125;=require(<span class="string">&quot;./list&quot;</span>)</span><br><span class="line">app.use(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    console.log(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">app.use(<span class="string">&quot;/view&quot;</span>,list);</span><br></pre></td></tr></table></figure>
<h4 id="路由中间件"><a href="#路由中间件" class="headerlink" title="路由中间件"></a>路由中间件</h4><p>参照上方路由内容</p>
<h4 id="第三方中间件"><a href="#第三方中间件" class="headerlink" title="第三方中间件"></a>第三方中间件</h4><p>比如我们在前面使用过body-parser,这里也是中间件的使用</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">const bodyParser=require(<span class="string">&quot;body-parser&quot;</span>);</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">// parse application/x-www-form-urlencode</span><br><span class="line">app.use(bodyParser.urlencoded(&#123;extended:<span class="literal">false</span>&#125;));</span><br><span class="line">// parse application/json</span><br><span class="line">app.use(bodyParser.json());</span><br><span class="line"></span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(req.body);</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="内置中间件"><a href="#内置中间件" class="headerlink" title="内置中间件"></a>内置中间件</h4><p>在express中内置中间件仅有一个，就是静态处理，可以快速将静态文件返回给前端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app.use(express.static(<span class="string">&quot;./public&quot;</span>));</span><br></pre></td></tr></table></figure>
<p>在页面中如果设置静态目录为public文件夹下，那么通过路径访问的目录就是这个public目录下的所有文件和内容</p>
<p>前面我们有个node案例是创建站点静态目录，我们这里只需要一句话就可以完成</p>
<h4 id="错误处理中间件"><a href="#错误处理中间件" class="headerlink" title="错误处理中间件"></a>错误处理中间件</h4><p>错误处理中间件有 4 个参数，定义错误处理中间件时必须使用这 4 个参数。即使不需要 next 对象，也必须在签名中声明它，否则中间件会被识别为一个常规中间件，不能处理错误。</p>
<p>错误处理中间件和其他中间件定义类似，只是要使用 4 个参数，而不是 3 个，其签名如下： (err, req, res, next)。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">app.use(<span class="keyword">function</span>(err, req, res, next) &#123;</span><br><span class="line">  console.error(err.stack)</span><br><span class="line">  res.status(500).send(<span class="string">&#x27;Something broke!&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/27/express-base/"><span>express-base</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/27/express-base/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-27T07:27:47.000Z">
          2021-01-27
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="Express基础"><a href="#Express基础" class="headerlink" title="Express基础"></a>Express基础</h2><p>基于 Node.js 平台，快速、开放、极简的 web 开发框架。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">npm install express --save</span><br><span class="line">或者</span><br><span class="line">yarn add express -S</span><br></pre></td></tr></table></figure>
<h3 id="一、特色"><a href="#一、特色" class="headerlink" title="一、特色"></a>一、特色</h3><h4 id="1、Web-应用"><a href="#1、Web-应用" class="headerlink" title="1、Web 应用"></a>1、Web 应用</h4><p>Express 是一个基于 Node.js 平台的极简、灵活的 web 应用开发框架，它提供一系列强大的特性，帮助你创建各种 Web 和移动设备应用。</p>
<h4 id="2、API"><a href="#2、API" class="headerlink" title="2、API"></a>2、API</h4><p>丰富的 HTTP 快捷方法和任意排列组合的 Connect 中间件，让你创建健壮、友好的 API 变得既快速又简单。</p>
<h4 id="3、性能"><a href="#3、性能" class="headerlink" title="3、性能"></a>3、性能</h4><p>Express 不对 Node.js 已有的特性进行二次抽象，我们只是在它之上扩展了 Web 应用所需的基本功能。</p>
<h3 id="二、安装"><a href="#二、安装" class="headerlink" title="二、安装"></a>二、安装</h3><p>首先假定你已经安装了 Node.js，接下来为你的应用创建一个目录，然后进入此目录并将其作为当前工作目录。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mkdir myapp</span><br><span class="line"><span class="built_in">cd</span> myapp</span><br></pre></td></tr></table></figure>
<p>通过 npm init 命令为你的应用创建一个 package.json 文件。 欲了解 package.json 是如何起作用的，请参考 Specifics of npm’s package.json handling。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm init</span><br></pre></td></tr></table></figure>
<p>此命令将要求你输入几个参数，例如此应用的名称和版本。 你可以直接按“回车”键接受默认设置即可，下面这个除外：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">entry point: (index.js)</span><br></pre></td></tr></table></figure>
<p>键入 app.js 或者你所希望的名称，这是当前应用的入口文件。如果你希望采用默认的 index.js 文件名，只需按“回车”键即可。</p>
<p>接下来安装 Express 并将其保存到依赖列表中：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install express --save</span><br></pre></td></tr></table></figure>
<p>如果只是临时安装 Express，不想将它添加到依赖列表中，只需略去 –save 参数即可：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install express</span><br></pre></td></tr></table></figure>
<p>安装 Node 模块时，如果指定了 –save 参数，那么此模块将被添加到 package.json 文件中 dependencies 依赖列表中。 然后通过 npm install 命令即可自动安装依赖列表中所列出的所有模块。</p>
<h3 id="三、Hello-world-实例"><a href="#三、Hello-world-实例" class="headerlink" title="三、Hello world 实例"></a>三、Hello world 实例</h3><p>接下来，我们一起创建一个基本的 Express 应用。</p>
<p>注意：这里所创建是一个最最简单的 Express 应用，并且仅仅只有一个文件 — 和通过 Express 应用生成器 所创建的应用完全不一样，Express 应用生成器所创建的应用框架包含多 JavaScript 文件、Jade 模板和针对不同用途的子目录。</p>
<p>进入 myapp 目录，创建一个名为 app.js 的文件，然后将下列代码复制进去：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">var express = require(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line">var app = express();</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&#x27;/&#x27;</span>, <span class="keyword">function</span> (req, res) &#123;</span><br><span class="line">  res.send(<span class="string">&#x27;Hello World!&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">var server = app.listen(3000, <span class="function"><span class="title">function</span></span> () &#123;</span><br><span class="line">  var host = server.address().address;</span><br><span class="line">  var port = server.address().port;</span><br><span class="line"></span><br><span class="line">  console.log(<span class="string">&#x27;Example app listening at http://%s:%s&#x27;</span>, host, port);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面的代码启动一个服务并监听从 3000 端口进入的所有连接请求。他将对所有 (/) URL 或 路由 返回 “Hello World!” 字符串。对于其他所有路径全部返回 404 Not Found。</p>
<p>req (请求) 和 res (响应) 与 Node 提供的对象完全一致，因此，你可以调用 req.pipe()、req.on(‘data’, callback) 以及任何 Node 提供的方法。</p>
<p>通过如下命令启动此应用：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node app.js</span><br></pre></td></tr></table></figure>
<p>然后在浏览器中打开 [<a target="_blank" rel="noopener" href="http://localhost:3000/]">http://localhost:3000/]</a> 并查看输出结果</p>
<h3 id="四、express的通信应用"><a href="#四、express的通信应用" class="headerlink" title="四、express的通信应用"></a>四、express的通信应用</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">const express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">const app=express();</span><br></pre></td></tr></table></figure>
<h4 id="app-get"><a href="#app-get" class="headerlink" title="app.get"></a>app.get</h4><p>主要用于前后端get通信方式处理</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="app-post"><a href="#app-post" class="headerlink" title="app.post"></a>app.post</h4><p>主要用于前后端post通信方式处理</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="app-put-app-delete-app-all"><a href="#app-put-app-delete-app-all" class="headerlink" title="app.put,app.delete,app.all"></a>app.put,app.delete,app.all</h4><p>1、GET请求会向数据库发索取数据的请求，从而来获取信息，该请求就像数据库的select操作一样，只是用来查询一下数据，不会修改、增加数据，不会影响资源的内容，即该请求不会产生副作用。无论进行多少次操作，结果都是一样的。</p>
<p>2、与GET不同的是，PUT请求是向服务器端发送数据的，从而改变信息，该请求就像数据库的update操作一样，用来修改数据的内容，但是不会增加数据的种类等，也就是说无论进行多少次PUT操作，其结果并没有不同。</p>
<p>3、POST请求同PUT请求类似，都是向服务器端发送数据的，但是该请求会改变数据的种类等资源，就像数据库的insert操作一样，会创建新的内容。几乎目前所有的提交操作都是用POST请求的。</p>
<p>4、DELETE请求顾名思义，就是用来删除某一个资源的，该请求就像数据库的delete操作。</p>
<p>app.all是不管哪种都可以接收</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">//app.put(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">//    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">//&#125;)</span><br><span class="line">//app.delete(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">//    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">//&#125;)</span><br><span class="line">//app.all(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">//    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">//&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="app-use"><a href="#app-use" class="headerlink" title="app.use"></a>app.use</h4><p>use一般用于中间件，目的是在发送之前，或者某件事件之前先做一些处理，例如提前处理一些数据<br>后面我们会详细讲解各种中间价的处理</p>
<p>注意use后面的第二个函数中有3个参数，第一个是req，第二个是res，第三个是next<br>我们在use中处理完内容后，必须执行next()这样才可以进入后续的内容，否则将不会向后继续执行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);//例如在这里处理跨域问题</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(<span class="string">&quot;bb&quot;</span>);</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="app-engine"><a href="#app-engine" class="headerlink" title="app.engine"></a>app.engine</h4><p>注册扩展名解析，如果遇到某种扩展名，使用某个方法解析该扩展名的文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">app.engine(<span class="string">&quot;art&quot;</span>,require(<span class="string">&quot;express-art-template&quot;</span>));</span><br><span class="line">//遇到art扩展名文件，使用express-art-template插件解析</span><br></pre></td></tr></table></figure>
<h4 id="app-set"><a href="#app-set" class="headerlink" title="app.set"></a>app.set</h4><p>部分第三方的一些插件在express框架中使用时需要设置一些基础参数，便于在使用时直接调用，这里有一部分是固定属性，也可以自定义属性</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//设置views文件夹也就是模板文件夹，对于调用的路径是view文件夹下</span><br><span class="line">app.set(<span class="string">&quot;views&quot;</span>,path.join(__dirname,<span class="string">&quot;./view&quot;</span>));</span><br><span class="line">//设置视图解析的方式是通过art这个注册的插件</span><br><span class="line">app.set(<span class="string">&quot;view engine&quot;</span>,<span class="string">&quot;art&quot;</span>);</span><br></pre></td></tr></table></figure>
<h3 id="五、express中请求的部分属性"><a href="#五、express中请求的部分属性" class="headerlink" title="五、express中请求的部分属性"></a>五、express中请求的部分属性</h3><p>主要使用在各种get，post，use等app应用的第二个函数中的req的属性</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">   //req 这里的req就是请求数据的内容</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="req-query"><a href="#req-query" class="headerlink" title="req.query"></a>req.query</h4><p>获取get通过地址传参方式传过来的参数</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);//例如在这里处理跨域问题</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(req.query);</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="req-body"><a href="#req-body" class="headerlink" title="req.body"></a>req.body</h4><p>获取post通过地址传参方式传过来的参数,但是node并不会自动解析传过来的数据，所以需要一个额外的插件用来解析，这个插件普通我们通常使用body-parser解析</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i body-parser -S</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">const bodyParser=require(<span class="string">&quot;body-parser&quot;</span>);</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">// parse application/x-www-form-urlencode</span><br><span class="line">app.use(bodyParser.urlencoded(&#123;extended:<span class="literal">false</span>&#125;));</span><br><span class="line">// parse application/json</span><br><span class="line">app.use(bodyParser.json());</span><br><span class="line"></span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(req.body);</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<p>例如解析formdata数据用到的插件multer</p>
<p>下载</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i multer -S</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">const bodyParser=require(<span class="string">&quot;body-parser&quot;</span>);</span><br><span class="line">const multer=require(<span class="string">&quot;multer&quot;</span>)();//载入并且执行函数返回对象</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">// parse application/x-www-form-urlencode</span><br><span class="line">app.use(bodyParser.urlencoded(&#123;extended:<span class="literal">false</span>&#125;));</span><br><span class="line">// parse application/json</span><br><span class="line">app.use(bodyParser.json());</span><br><span class="line">// parse application/formdata</span><br><span class="line">app.use(multer.none());</span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(req.body);</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h3 id="req-path"><a href="#req-path" class="headerlink" title="req.path"></a>req.path</h3><p>获取当前路径</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>&#125;);//例如在这里处理跨域问题</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    console.log(req.path);//path 是/a</span><br><span class="line">    res.send(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h3 id="六、express中响应的部分属性"><a href="#六、express中响应的部分属性" class="headerlink" title="六、express中响应的部分属性"></a>六、express中响应的部分属性</h3><p>主要使用在各种get，post，use等app应用的第二个函数中的res的属性</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line">app.post(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">   //res 这里的req就是请求数据的内容</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-send"><a href="#res-send" class="headerlink" title="res.send"></a>res.send</h4><p>用于发送数据给前端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.send(Buffer.from(<span class="string">&#x27;whoop&#x27;</span>))//可以发送Buffer</span><br><span class="line">    // res.send(&#123; some: <span class="string">&#x27;json&#x27;</span> &#125;)//可以直接发送Json</span><br><span class="line">    // res.send(<span class="string">&#x27;&lt;p&gt;some html&lt;/p&gt;&#x27;</span>)//可以发送字符</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-status"><a href="#res-status" class="headerlink" title="res.status"></a>res.status</h4><p>返回状态码并且发送</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.status(404).send(<span class="string">&#x27;Sorry, we cannot find that!&#x27;</span>)//可以设置响应的状态的同事发送</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-set"><a href="#res-set" class="headerlink" title="res.set"></a>res.set</h4><p>设置响应头</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;Content-Type&#x27;</span>:<span class="string">&#x27;text/html;charset=utf-8&#x27;</span></span><br><span class="line">    &#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">   res.send(<span class="string">&#x27;aaa&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-type"><a href="#res-type" class="headerlink" title="res.type"></a>res.type</h4><p>设置响应头消息的MIME类型</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    res.type(<span class="string">&quot;json&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.send(&#123;a:1,b:2&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-json"><a href="#res-json" class="headerlink" title="res.json"></a>res.json</h4><p>直接设置响应消息的MIME类型是json,并且将对象用json.stringfy转换直接发送</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.json(&#123;a:1,b:2&#125;);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="res-jsonp"><a href="#res-jsonp" class="headerlink" title="res.jsonp"></a>res.jsonp</h4><p>直接发送jsonp消息</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var express=require(<span class="string">&quot;express&quot;</span>);</span><br><span class="line">var app=express();</span><br><span class="line"></span><br><span class="line">app.use(<span class="string">&quot;/&quot;</span>,<span class="keyword">function</span>(req,res,next)&#123;</span><br><span class="line">    res.set(&#123;</span><br><span class="line">        <span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>:<span class="string">&#x27;*&#x27;</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(<span class="string">&quot;/a&quot;</span>,<span class="keyword">function</span>(req,res)&#123;</span><br><span class="line">    res.jsonp(&#123;a:1,b:2&#125;);//返回的消息在callback函数中调用</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(4001);</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/27/yarn/"><span>yarn</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/27/yarn/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-27T04:59:49.000Z">
          2021-01-27
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="Yarn-使用入门"><a href="#Yarn-使用入门" class="headerlink" title="Yarn 使用入门"></a>Yarn 使用入门</h2><p>Yarn 对你的代码来说是一个包管理器。它可以让你使用并分享全世界开发者的（例如 JavaScript）代码。 Yarn 能够快速、安全、并可靠地完成这些工作，所以你不用有任何担心。</p>
<p>通过Yarn你可以使用其他开发者针对不同问题的解决方案，使自己的开发过程更简单。</p>
<p>代码通过包（package） (或者称为 模块（module）) 的方式来共享。 一个包里包含所有需要共享的代码，以及描述包信息的文件，称为 package.json。</p>
<h3 id="1、安装"><a href="#1、安装" class="headerlink" title="1、安装"></a>1、安装</h3><p>yarn 安装请进 <a target="_blank" rel="noopener" href="https://yarn.bootcss.com/docs/install/#mac-stable">传送门</a></p>
<h3 id="2、Yarn-使用方法"><a href="#2、Yarn-使用方法" class="headerlink" title="2、Yarn 使用方法"></a>2、Yarn 使用方法</h3><p>现在 Yarn 已经 安装完毕，可以开始使用了。 以下是一些你需要的最常用的命令：</p>
<h3 id="2-1-初始化一个新项目"><a href="#2-1-初始化一个新项目" class="headerlink" title="2.1 初始化一个新项目"></a>2.1 初始化一个新项目</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn init</span><br></pre></td></tr></table></figure>
<h3 id="2-2-添加依赖包"><a href="#2-2-添加依赖包" class="headerlink" title="2.2 添加依赖包"></a>2.2 添加依赖包</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">yarn add [package]</span><br><span class="line">yarn add [package]@[version]</span><br><span class="line">yarn add [package]@[tag]</span><br></pre></td></tr></table></figure>
<h3 id="2-3-将依赖项添加到不同依赖项类别中"><a href="#2-3-将依赖项添加到不同依赖项类别中" class="headerlink" title="2.3 将依赖项添加到不同依赖项类别中"></a>2.3 将依赖项添加到不同依赖项类别中</h3><p>分别添加到 devDependencies、peerDependencies 和 optionalDependencies 类别中：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">yarn add [package] --dev</span><br><span class="line">yarn add [package] --peer</span><br><span class="line">yarn add [package] --optional</span><br><span class="line">devDependencies、peerDependencies 和 optionalDependencies区别</span><br></pre></td></tr></table></figure>
<p>在一个Node.js项目中，package.json几乎是一个必须的文件，它的主要作用就是管理项目中所使用到的外部依赖包，同时它也是npm命令的入口文件。</p>
<p>npm 目前支持以下几类依赖包管理：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">dependencies</span><br><span class="line">devDependencies</span><br><span class="line">peerDependencies</span><br><span class="line">optionalDependencies</span><br><span class="line">bundledDependencies / bundleDependencies</span><br></pre></td></tr></table></figure>
<p>dependencies</p>
<p>应用依赖，或者叫做业务依赖，这是我们最常用的依赖包管理对象！它用于指定应用依赖的外部包，这些依赖是应用发布后正常执行时所需要的，但不包含测试时或者本地打包时所使用的包。</p>
<p>devDependencies</p>
<p>开发环境依赖，仅次于dependencies的使用频率！它的对象定义和dependencies一样，只不过它里面的包只用于开发环境，不用于生产环境，这些包通常是单元测试或者打包工具等，例如gulp, grunt, webpack, moca, coffee等。</p>
<p>peerDependencies</p>
<p>同等依赖，或者叫同伴依赖，用于指定当前包（也就是你写的包）兼容的宿主版本。如何理解呢？ 试想一下，我们编写一个gulp的插件，而gulp却有多个主版本，我们只想兼容最新的版本，此时就可以用同等依赖（peerDependencies）来指定。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">&quot;name&quot;</span>: <span class="string">&quot;gulp-my-plugin&quot;</span>,</span><br><span class="line">  <span class="string">&quot;version&quot;</span>: <span class="string">&quot;0.0.1&quot;</span>,</span><br><span class="line">  <span class="string">&quot;peerDependencies&quot;</span>: &#123;</span><br><span class="line">    <span class="string">&quot;gulp&quot;</span>: <span class="string">&quot;3.x&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>optionalDependencies</p>
<p>可选依赖，如果有一些依赖包即使安装失败，项目仍然能够运行或者希望npm继续运行，就可以使用optionalDependencies。另外optionalDependencies会覆盖dependencies中的同名依赖包，所以不要在两个地方都写。</p>
<p>bundledDependencies / bundleDependencies</p>
<p>打包依赖，bundledDependencies是一个包含依赖包名的数组对象，在发布时会将这个对象中的包打包到最终的发布包里。</p>
<h3 id="2-4-升级依赖包"><a href="#2-4-升级依赖包" class="headerlink" title="2.4 升级依赖包"></a>2.4 升级依赖包</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">yarn upgrade [package]</span><br><span class="line">yarn upgrade [package]@[version]</span><br><span class="line">yarn upgrade [package]@[tag]</span><br></pre></td></tr></table></figure>
<h3 id="2-5-移除依赖包"><a href="#2-5-移除依赖包" class="headerlink" title="2.5 移除依赖包"></a>2.5 移除依赖包</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn remove [package]</span><br></pre></td></tr></table></figure>
<h3 id="2-6-安装项目的全部依赖"><a href="#2-6-安装项目的全部依赖" class="headerlink" title="2.6 安装项目的全部依赖"></a>2.6 安装项目的全部依赖</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">yarn</span><br><span class="line">或者</span><br><span class="line">yarn install</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/27/staticPath/"><span>staticPath</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/27/staticPath/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-27T04:48:11.000Z">
          2021-01-27
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="静态资源目录案例"><a href="#静态资源目录案例" class="headerlink" title="静态资源目录案例"></a>静态资源目录案例</h2><h3 id="服务器静态地址目录"><a href="#服务器静态地址目录" class="headerlink" title="服务器静态地址目录"></a>服务器静态地址目录</h3><p>前端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;ul&gt;&lt;/ul&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line"></span><br><span class="line">        var ul;</span><br><span class="line">        init();</span><br><span class="line">        <span class="keyword">function</span> <span class="function"><span class="title">init</span></span>()&#123;</span><br><span class="line">            ul=document.querySelector(<span class="string">&quot;ul&quot;</span>);</span><br><span class="line">            ul.addEventListener(<span class="string">&quot;click&quot;</span>,clickHandler);</span><br><span class="line">            window.addEventListener(<span class="string">&quot;popstate&quot;</span>,stateHandler);</span><br><span class="line">            ajax();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> ajax(data)&#123;</span><br><span class="line">            var xhr=new XMLHttpRequest();</span><br><span class="line">            xhr.addEventListener(<span class="string">&quot;load&quot;</span>,loadHandler);</span><br><span class="line">            xhr.open(<span class="string">&quot;post&quot;</span>,<span class="string">&quot;http://localhost:4001&quot;</span>);</span><br><span class="line">            xhr.send(data);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> loadHandler(e)&#123;</span><br><span class="line">            var list=JSON.parse(e.target.response);</span><br><span class="line">            history.pushState(list,<span class="string">&quot;&quot;</span>);</span><br><span class="line">            setUList(list);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> setUList(list)&#123;</span><br><span class="line">            ul.innerHTML=list.reduce((value,item)=&gt;&#123;</span><br><span class="line">                var arr=item.value.split(<span class="string">&quot;\\&quot;</span>);</span><br><span class="line">                var names=arr.pop();</span><br><span class="line">                var path=arr.join(<span class="string">&quot;\\&quot;</span>)+<span class="string">&quot;\\&quot;</span>;</span><br><span class="line">                <span class="built_in">return</span> value+`&lt;li&gt;<span class="variable">$&#123;item.file ? names : &quot;&lt;a href=&#x27;javascript:void(0)&#x27; path=&#x27;&quot;+path+&quot;&#x27;&gt;&quot;+names+&quot;&lt;/a&gt;&quot;&#125;</span>&lt;/li&gt;`</span><br><span class="line">            &#125;,<span class="string">&quot;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> stateHandler(e)&#123;</span><br><span class="line">            setUList(e.state);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> clickHandler(e)&#123;</span><br><span class="line">            <span class="keyword">if</span>(e.target.nodeName!==<span class="string">&quot;A&quot;</span>)<span class="built_in">return</span>;</span><br><span class="line">            // ajax(e.target.textContent.replace(/\\/g,<span class="string">&quot;\\\\&quot;</span>)+<span class="string">&quot;\\&quot;</span>);</span><br><span class="line">            var path=e.target.getAttribute(<span class="string">&quot;path&quot;</span>).replace(/\\/g,<span class="string">&quot;\\&quot;</span>);</span><br><span class="line">            ajax(path+e.target.textContent+<span class="string">&quot;\\&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<p>服务端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">var http=require(<span class="string">&quot;http&quot;</span>);</span><br><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> createServer(fn)&#123;</span><br><span class="line">        http.createServer((inComeMsg,response)=&gt;&#123;</span><br><span class="line">            response.writeHead(200,&#123;</span><br><span class="line">                <span class="string">&quot;Access-Control-Allow-Origin&quot;</span>:<span class="string">&quot;*&quot;</span></span><br><span class="line">            &#125;)</span><br><span class="line">            var data=<span class="string">&quot;&quot;</span>;</span><br><span class="line">            inComeMsg.on(<span class="string">&quot;data&quot;</span>,_data=&gt;data+=_data);</span><br><span class="line">            inComeMsg.on(<span class="string">&#x27;end&#x27;</span>,()=&gt;&#123;</span><br><span class="line">                fn(&#123;data:data,res:response&#125;);</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;).listen(4001);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> getPathList(src)&#123;</span><br><span class="line">   <span class="keyword">if</span>(src===<span class="string">&quot;&quot;</span>) src=<span class="string">&quot;D:\\&quot;</span>;</span><br><span class="line">    <span class="built_in">return</span> new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">        fs.readdir(src,(error,data)=&gt;&#123;</span><br><span class="line">          var dirlist=[]</span><br><span class="line">          var fileList=[];</span><br><span class="line">          data.forEach(item=&gt;&#123;</span><br><span class="line">              try&#123;</span><br><span class="line">                var <span class="built_in">stat</span>=fs.statSync(src+item);</span><br><span class="line">                <span class="keyword">if</span>(stat.isFile())fileList.push(&#123;value:src+item,file:stat.isFile()&#125;)</span><br><span class="line">                <span class="keyword">else</span> dirlist.push(&#123;value:src+item,file:stat.isFile()&#125;)</span><br><span class="line">              &#125;catch(e)&#123;</span><br><span class="line"></span><br><span class="line">              &#125;</span><br><span class="line">          &#125;)</span><br><span class="line">            resolve(dirlist.concat(fileList));</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">createServer((&#123;data,res&#125;)=&gt;&#123;</span><br><span class="line">    getPathList(data).<span class="keyword">then</span>(list=&gt;&#123;</span><br><span class="line">        res.end(JSON.stringify(list));</span><br><span class="line">    &#125;)</span><br><span class="line"> &#125;)</span><br></pre></td></tr></table></figure>
<h3 id="静态资源目录"><a href="#静态资源目录" class="headerlink" title="静态资源目录"></a>静态资源目录</h3><p>服务端a.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">var path=require(<span class="string">&quot;path&quot;</span>);</span><br><span class="line">var mime=require(<span class="string">&quot;mime&quot;</span>);//mime插件，用来获取文件是否类型</span><br><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> myReadFile(file)&#123;</span><br><span class="line">   <span class="built_in">return</span> new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">        fs.readFile(file,(err,data)=&gt;&#123;</span><br><span class="line">            <span class="keyword">if</span>(err)&#123;</span><br><span class="line">                reject(null);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                resolve(data);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">   &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">async <span class="keyword">function</span> readStaticFile(filePathName)&#123;</span><br><span class="line">    <span class="built_in">let</span> ext=path.parse(filePathName).ext;//是否有扩展名</span><br><span class="line">    <span class="built_in">let</span> mimeType=mime.getType(ext) || <span class="string">&quot;text/html&quot;</span>;//获取这个扩展名对应的文件类型</span><br><span class="line">    <span class="built_in">let</span> data=null;</span><br><span class="line">    <span class="keyword">if</span>(fs.existsSync(filePathName))&#123;</span><br><span class="line">        <span class="keyword">if</span>(ext)&#123;</span><br><span class="line">            await myReadFile(filePathName).<span class="keyword">then</span>(_data=&gt;data=_data).catch(err=&gt;data=err);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            await myReadFile(path.join(filePathName,<span class="string">&quot;./index.html&quot;</span>)).<span class="keyword">then</span>(_data=&gt;data=_data).catch(err=&gt;data=err);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">return</span> &#123;data,mimeType&#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module.exports=readStaticFile;</span><br></pre></td></tr></table></figure>
<p>b.js</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var http=require(<span class="string">&quot;http&quot;</span>);</span><br><span class="line">var path=require(<span class="string">&quot;path&quot;</span>);</span><br><span class="line">var readStaticFile=require(<span class="string">&quot;./a&quot;</span>);</span><br><span class="line">http.createServer((inCommMeg,response)=&gt;&#123;</span><br><span class="line">    <span class="built_in">let</span> urlString=inCommMeg.url;</span><br><span class="line">    <span class="built_in">let</span> filePathName=path.join(__dirname,urlString);</span><br><span class="line">    console.log(filePathName);</span><br><span class="line">    readStaticFile(filePathName).<span class="keyword">then</span>((&#123;data,mimeType&#125;)=&gt;&#123;</span><br><span class="line">        console.log(data);</span><br><span class="line">        response.writeHead(200,&#123;</span><br><span class="line">            <span class="string">&quot;Content-type&quot;</span>:mimeType+<span class="string">&quot;;charset=utf-8&quot;</span>,</span><br><span class="line">            <span class="string">&quot;Access-Control-Allow-Origin&quot;</span>:<span class="string">&quot;*&quot;</span></span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">if</span>(!data) response.write(<span class="string">&quot;错误的数据&quot;</span>);</span><br><span class="line">        <span class="keyword">else</span> response.write(data);</span><br><span class="line">        response.end();</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;).listen(4001);</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/26/route/"><span>route</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/26/route/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-26T12:44:30.000Z">
          2021-01-26
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h2><p>通过下述案例我们理解一下路由的基本概念，这是一个根据路径完成的类似状态匹配的分支处理概念</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">ar http = require(<span class="string">&#x27;http&#x27;</span>)</span><br><span class="line">var fs = require(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"></span><br><span class="line">http.createServer( <span class="keyword">function</span> ( req, res ) &#123;</span><br><span class="line"></span><br><span class="line">  switch ( req.url ) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;/home&#x27;</span>:</span><br><span class="line">      res.write(<span class="string">&#x27;home&#x27;</span>)</span><br><span class="line">      res.end()</span><br><span class="line">      <span class="built_in">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;/mine&#x27;</span>:</span><br><span class="line">      res.write(<span class="string">&#x27;mine&#x27;</span>)</span><br><span class="line">      res.end()</span><br><span class="line">      <span class="built_in">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;/login&#x27;</span>: </span><br><span class="line">      fs.readFile( <span class="string">&#x27;./static/login.html&#x27;</span>,<span class="keyword">function</span> ( error , data ) &#123;</span><br><span class="line">        <span class="keyword">if</span> ( error ) throw error  </span><br><span class="line">        res.write( data )</span><br><span class="line">        res.end()</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="built_in">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;/fulian.jpg&#x27;</span>:</span><br><span class="line">      fs.readFile( <span class="string">&#x27;./static/fulian.jpg&#x27;</span>, <span class="string">&#x27;binary&#x27;</span>, <span class="keyword">function</span>( error , data ) &#123;</span><br><span class="line">        <span class="keyword">if</span>( error ) throw error </span><br><span class="line">        res.write( data, <span class="string">&#x27;binary&#x27;</span> )</span><br><span class="line">        res.end()</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="built_in">break</span></span><br><span class="line">    default: </span><br><span class="line">      <span class="built_in">break</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"> &#125;).listen( 8000, <span class="string">&#x27;localhost&#x27;</span>, <span class="function"><span class="title">function</span></span> () &#123;</span><br><span class="line">   console.log( <span class="string">&#x27;服务器运行在： http://localhost:8000&#x27;</span> )</span><br><span class="line"> &#125;)</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/26/file/"><span>file</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/26/file/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-26T07:13:24.000Z">
          2021-01-26
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="7、file"><a href="#7、file" class="headerlink" title="7、file"></a>7、file</h2><h3 id="引入"><a href="#引入" class="headerlink" title="引入"></a>引入</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br></pre></td></tr></table></figure>
<h4 id="fs-mkdir"><a href="#fs-mkdir" class="headerlink" title="fs.mkdir"></a>fs.mkdir</h4><p>创建文件夹</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.mkdir(<span class="string">&#x27;./logs&#x27;</span>, (err) =&gt; &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;done.&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-rmdir"><a href="#fs-rmdir" class="headerlink" title="fs.rmdir"></a>fs.rmdir</h4><p>删除文件夹</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.rmdir(<span class="string">&#x27;./log&#x27;</span>, () =&gt; &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;done.&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-existsSync"><a href="#fs-existsSync" class="headerlink" title="fs.existsSync"></a>fs.existsSync</h4><p>判断路径是否存在 同步方法</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (fs.existsSync(<span class="string">&#x27;path&#x27;</span>)) &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;该路径已存在&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="fs-readFile"><a href="#fs-readFile" class="headerlink" title="fs.readFile"></a>fs.readFile</h4><p>异步读取文件.注意地址中会有转义字符,所以\使用的时候要多敲一个</p>
<p>异步读取方法1</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">fs.readFile(<span class="string">&quot;E:\\test\\test10\\server\\config.json&quot;</span>,<span class="string">&quot;utf8&quot;</span>,<span class="keyword">function</span>(err,data)&#123;</span><br><span class="line">    console.log(err);</span><br><span class="line">    console.log(data.toString());</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>异步读取方法2</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.readFile(<span class="string">&#x27;./logs/log-0.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>).<span class="keyword">then</span>(result =&gt; &#123;</span><br><span class="line">  console.log(result)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>异步读取方法3</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="function"><span class="title">getFile</span></span>() &#123;</span><br><span class="line">  <span class="built_in">return</span> new Promise((resolve) =&gt; &#123;</span><br><span class="line">    fs.readFile(<span class="string">&#x27;./logs/log-0.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>, (err, data) =&gt; &#123;</span><br><span class="line">      resolve(data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">;(async () =&gt; &#123;</span><br><span class="line">  console.log(await getFile())</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>异步读取方法4</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">const fsP = require(<span class="string">&#x27;fs&#x27;</span>).promises</span><br><span class="line">const fsp = fsP.readFile(<span class="string">&#x27;./logs/log-1.txt&#x27;</span>, <span class="string">&#x27;utf-8&#x27;</span>).<span class="keyword">then</span>((result) =&gt; &#123;</span><br><span class="line">  console.log(result)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">console.log(fsP)</span><br></pre></td></tr></table></figure>
<h4 id="fs-readFileSync"><a href="#fs-readFileSync" class="headerlink" title="fs.readFileSync"></a>fs.readFileSync</h4><p>同步读取文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">var data=fs.readFileSync(<span class="string">&quot;E:\\test\\test10\\server\\config.json&quot;</span>,<span class="string">&quot;utf8&quot;</span>);</span><br><span class="line">console.log(data.toString());</span><br></pre></td></tr></table></figure>
<h4 id="fs-createReadStream"><a href="#fs-createReadStream" class="headerlink" title="fs.createReadStream"></a>fs.createReadStream</h4><p>读取流模式</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">var stream=fs.createReadStream(<span class="string">&quot;E:\\test\\test10\\server\\config.json&quot;</span>);</span><br><span class="line">var data=<span class="string">&quot;&quot;</span>;</span><br><span class="line">stream.on(<span class="string">&quot;data&quot;</span>,<span class="keyword">function</span>(_data)&#123;</span><br><span class="line">    data+=_data;</span><br><span class="line">&#125;);</span><br><span class="line">stream.on(<span class="string">&quot;end&quot;</span>,<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">    console.log(data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-readline"><a href="#fs-readline" class="headerlink" title="fs.readline"></a>fs.readline</h4><p>逐行读取文本内容，这里需要引入一个逐行读取的模块</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var readline=require(<span class="string">&quot;readline&quot;</span>);</span><br></pre></td></tr></table></figure>
<p>readline.createInterface会将读取到的文件流存在一个读取列表中，通过line事件读入每行的内容</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">var readline=require(<span class="string">&quot;readline&quot;</span>);</span><br><span class="line">var rl=readline.createInterface(fs.createReadStream(<span class="string">&quot;./server/data/a.txt&quot;</span>));</span><br><span class="line">rl.on(<span class="string">&quot;line&quot;</span>,<span class="keyword">function</span>(line)&#123;</span><br><span class="line">    console.log(line);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-stat"><a href="#fs-stat" class="headerlink" title="fs.stat"></a>fs.stat</h4><p>读取目录和文件信息</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">fs.readdir(<span class="string">&#x27;./&#x27;</span>, (err, data) =&gt; &#123;</span><br><span class="line">  data.forEach((value, index) =&gt; &#123;</span><br><span class="line">    fs.stat(`./<span class="variable">$&#123;value&#125;</span>`, (err, stats) =&gt; &#123;</span><br><span class="line">      // console.log(value + <span class="string">&#x27;:&#x27;</span> + stats.size)</span><br><span class="line">      console.log(value + <span class="string">&#x27; is &#x27;</span> + (stats.isDirectory() ? <span class="string">&#x27;directory&#x27;</span> : <span class="string">&#x27;file&#x27;</span>))</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>获取当前指定文件夹下所有的文件和文件夹</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">getDir(<span class="string">&quot;./&quot;</span>)</span><br><span class="line"><span class="keyword">function</span> getDir(path)&#123;</span><br><span class="line">    fs.readdir(path, (err, data) =&gt; &#123;</span><br><span class="line">        data.forEach((value, index) =&gt; &#123;</span><br><span class="line">          fs.stat(`<span class="variable">$&#123;path+value&#125;</span>`, (err, stats) =&gt; &#123;</span><br><span class="line">             <span class="keyword">if</span>(!stats)<span class="built_in">return</span>;</span><br><span class="line">            // console.log(value + <span class="string">&#x27;:&#x27;</span> + stats.size)</span><br><span class="line">            console.log(value + <span class="string">&#x27; is &#x27;</span> + (stats.isDirectory() ? <span class="string">&#x27;directory&#x27;</span> : <span class="string">&#x27;file&#x27;</span>))</span><br><span class="line">            <span class="keyword">if</span>(stats.isDirectory())&#123;</span><br><span class="line">                getDir(path+value+<span class="string">&quot;/&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="fs-statSync"><a href="#fs-statSync" class="headerlink" title="fs.statSync"></a>fs.statSync</h4><p>对象提供有关文件的信息</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var stats=fs.statSync(path);</span><br><span class="line">stats.isFile() //判断当前路径的是不是文件</span><br></pre></td></tr></table></figure>
<h4 id="fs-readdir"><a href="#fs-readdir" class="headerlink" title="fs.readdir"></a>fs.readdir</h4><p>异步读取文件的内容.回调有两个参数 (err, files)，其中 files 是目录中的文件名的数组（不包括 ‘.’ 和 ‘..’）。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.readdir(path,<span class="keyword">function</span>(error,files)&#123;</span><br><span class="line">    //files是一个数组,里面包含了当前路径下所有的文件和文件夹名称</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-readdirSync"><a href="#fs-readdirSync" class="headerlink" title="fs.readdirSync"></a>fs.readdirSync</h4><p>同步读取路径当中的内容</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var files=fs.readdirSync(path);</span><br></pre></td></tr></table></figure>
<h4 id="fs-writeFile"><a href="#fs-writeFile" class="headerlink" title="fs.writeFile"></a>fs.writeFile</h4><p>异步地将数据写入到一个文件，如果文件已存在则覆盖该文件。 data 可以是字符串或 buffer。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">fs.writeFile(<span class="string">&#x27;a.txt&#x27;</span>, <span class="string">&#x27;文本内容&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>, <span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="fs-writeFileSync"><a href="#fs-writeFileSync" class="headerlink" title="fs.writeFileSync"></a>fs.writeFileSync</h4><p>异步写入文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fs.writeFileSync(<span class="string">&#x27;c:\\demo\a.txt&#x27;</span>, <span class="string">&quot;文本内容&quot;</span>);</span><br></pre></td></tr></table></figure>
<h4 id="fs-appendFile"><a href="#fs-appendFile" class="headerlink" title="fs.appendFile"></a>fs.appendFile</h4><p>向文件尾部增加新数据,如果该文件不存在就会创建一个新文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.appendFile(<span class="string">&quot;./server/data/a.txt&quot;</span>,<span class="string">&quot;新增的内容&quot;</span>,<span class="keyword">function</span>(error)&#123;</span><br><span class="line">    console.log(error);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-appendFileSync"><a href="#fs-appendFileSync" class="headerlink" title="fs.appendFileSync"></a>fs.appendFileSync</h4><p>同步向文件尾部增加新内容</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">try&#123;</span><br><span class="line">    fs.appendFileSync(<span class="string">&quot;./server/data/a.txt&quot;</span>,<span class="string">&quot;新增内容&quot;</span>);</span><br><span class="line">&#125;catch(e)&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="fs-rename"><a href="#fs-rename" class="headerlink" title="fs.rename"></a>fs.rename</h4><p>异步地把 oldPath 文件重命名为 newPath 提供的路径名。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">fs.rename(<span class="string">&#x27;旧文件.txt&#x27;</span>, <span class="string">&#x27;新文件.txt&#x27;</span>, (err) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) throw err;</span><br><span class="line">  console.log(<span class="string">&#x27;重命名完成&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="fs-unlink"><a href="#fs-unlink" class="headerlink" title="fs.unlink"></a>fs.unlink</h3><p>删除文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.unlink(<span class="string">&#x27;./logs/log1.txt&#x27;</span>, (err) =&gt; &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;done.&#x27;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="监视文件"><a href="#监视文件" class="headerlink" title="监视文件"></a>监视文件</h4><p>监视文件的变化</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">fs.watch(<span class="string">&#x27;./logs/log-0.txt&#x27;</span>, () =&gt; &#123;</span><br><span class="line">  console.log(0)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="fs-createWriteStream"><a href="#fs-createWriteStream" class="headerlink" title="fs.createWriteStream"></a>fs.createWriteStream</h4><p>流式写入,如果是大文件,内容较多,例如视频等就需要流式写入,防止内存卡死</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var streamWriter = fs.createWriteStream(<span class="string">&#x27;c:\\demo\a.txt&#x27;</span>);</span><br><span class="line">setInterval(<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">    streamWriter.write(`<span class="variable">$&#123;new Date&#125;</span>\n`, (error) =&gt; &#123;</span><br><span class="line">    console.log(error);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;,1000)</span><br></pre></td></tr></table></figure>
<h4 id="fs-createReadStream-1"><a href="#fs-createReadStream-1" class="headerlink" title="fs.createReadStream()"></a>fs.createReadStream()</h4><p>读取文件流</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const fs = require(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line">const readstream = fs.createReadStream(<span class="string">&#x27;./note.txt&#x27;</span>)</span><br><span class="line">const writestream = fs.createWriteStream(<span class="string">&#x27;./note2.txt&#x27;</span>)</span><br><span class="line">writestream.write(readstream)</span><br></pre></td></tr></table></figure>
<h4 id="zlib"><a href="#zlib" class="headerlink" title="zlib"></a>zlib</h4><p>压缩</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">const fs = require(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line">const zlib = require(<span class="string">&#x27;zlib&#x27;</span>)</span><br><span class="line"></span><br><span class="line">const gzip = zlib.createGzip()</span><br><span class="line">const readstream = fs.createReadStream(<span class="string">&#x27;./note.txt&#x27;</span>)</span><br><span class="line">const writestream = fs.createWriteStream(<span class="string">&#x27;./note2.txt&#x27;</span>)</span><br><span class="line">readstream</span><br><span class="line">  .pipe(gzip)</span><br><span class="line">  .pipe(writestream)</span><br><span class="line">writestream.write(readstream)</span><br></pre></td></tr></table></figure>
<h4 id="解析xlsx文件，Excel表格"><a href="#解析xlsx文件，Excel表格" class="headerlink" title="解析xlsx文件，Excel表格"></a>解析xlsx文件，Excel表格</h4><p>需要先下一个第三方模块node-xlsx,这里完成了一个excel表格筛选重建的内容然后创建一个新的表格文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">fs.readFile(<span class="string">&quot;G:\\abc.xlsx&quot;</span>,<span class="keyword">function</span>(error,data)&#123;</span><br><span class="line">   data=xlsx.parse(data);</span><br><span class="line">   var arr=data[0].data.slice(0,2);</span><br><span class="line">   data[0].data.forEach(item=&gt;&#123;</span><br><span class="line">       <span class="keyword">if</span>(String(item[0]).includes(<span class="string">&quot;刘&quot;</span>)) arr.push(item);</span><br><span class="line">   &#125;);</span><br><span class="line">   var buffer = xlsx.build([&#123;name: <span class="string">&quot;cde&quot;</span>, data: arr&#125;]);</span><br><span class="line">   fs.writeFile(<span class="string">&quot;G:\\cde.xlsx&quot;</span>,buffer,<span class="string">&quot;utf-8&quot;</span>,<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">       console.log(<span class="string">&quot;完成&quot;</span>);</span><br><span class="line">   &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="通过ajax上传图片并且保存在服务器"><a href="#通过ajax上传图片并且保存在服务器" class="headerlink" title="通过ajax上传图片并且保存在服务器"></a>通过ajax上传图片并且保存在服务器</h4><p>前端文件<br>注意var reader = new FileReader();这里是新建了一个文件渲染实例用来异步读取这个文件数据<br>reader.readAsArrayBuffer读取对应的文件<br>读取到的文件将会被放在reader.result中</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line"></span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;input <span class="built_in">type</span>=<span class="string">&quot;file&quot;</span>&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var file=document.querySelector(<span class="string">&quot;[type=file]&quot;</span>);</span><br><span class="line">        file.addEventListener(<span class="string">&quot;change&quot;</span>,sendFiles);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> <span class="function"><span class="title">sendFiles</span></span>() &#123;</span><br><span class="line">            var reader = new FileReader();</span><br><span class="line">            reader.readAsArrayBuffer(file.files[0]);</span><br><span class="line">            reader.addEventListener(<span class="string">&quot;load&quot;</span>,e=&gt;ajax(reader.result,file.files[0].name));</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">function</span> ajax(data,name)&#123;</span><br><span class="line">            var xhr=new XMLHttpRequest();</span><br><span class="line">            xhr.addEventListener(<span class="string">&quot;load&quot;</span>,loadHandler);</span><br><span class="line">            xhr.open(<span class="string">&quot;POST&quot;</span>,<span class="string">&quot;http://localhost:4001/&quot;</span>+name);</span><br><span class="line">            xhr.send(data);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">function</span> loadHandler(e)&#123;</span><br><span class="line"></span><br><span class="line">         &#125;</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<p>服务端文件</p>
<p>req.pipe是管道，将前端发送过来的数据通过管道发送存储文件流</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var http=require(<span class="string">&quot;http&quot;</span>);</span><br><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">http.createServer((req,res)=&gt;&#123;</span><br><span class="line">    res.writeHead(200,&#123;</span><br><span class="line">        <span class="string">&quot;content-type&quot;</span>:<span class="string">&quot;text/html;charset=utf-8&quot;</span>,</span><br><span class="line">        <span class="string">&quot;Access-Control-Allow-Origin&quot;</span>:<span class="string">&quot;*&quot;</span></span><br><span class="line">    &#125;);</span><br><span class="line">    req.pipe(fs.createWriteStream(<span class="string">&quot;./&quot;</span>+req.url,<span class="string">&quot;base64&quot;</span>));</span><br><span class="line">    res.end(<span class="string">&quot;完成了&quot;</span>);       </span><br><span class="line">&#125;).listen(4001);</span><br></pre></td></tr></table></figure>
<h4 id="使用formData数据上传多张图片"><a href="#使用formData数据上传多张图片" class="headerlink" title="使用formData数据上传多张图片"></a>使用formData数据上传多张图片</h4><p>客户端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;meta name=<span class="string">&quot;viewport&quot;</span> content=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line"></span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;form action=<span class="string">&quot;#&quot;</span>&gt;</span><br><span class="line">      &lt;input <span class="built_in">type</span>=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;user&quot;</span>&gt;</span><br><span class="line">    &lt;input <span class="built_in">type</span>=<span class="string">&quot;file&quot;</span> name=<span class="string">&quot;imgs&quot;</span> multiple&gt;</span><br><span class="line">    &lt;button <span class="built_in">type</span>=<span class="string">&quot;submit&quot;</span>&gt;提交&lt;/button&gt;</span><br><span class="line">  &lt;/form&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var form=document.querySelector(<span class="string">&quot;form&quot;</span>);</span><br><span class="line">        form.addEventListener(<span class="string">&quot;submit&quot;</span>,sendFiles);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">function</span> sendFiles(e) &#123;</span><br><span class="line">            e.preventDefault();</span><br><span class="line">            var data=new FormData(form);</span><br><span class="line">            ajax(data)</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">function</span> ajax(data)&#123;</span><br><span class="line">            var xhr=new XMLHttpRequest();</span><br><span class="line">            xhr.addEventListener(<span class="string">&quot;load&quot;</span>,loadHandler);</span><br><span class="line">            xhr.open(<span class="string">&quot;POST&quot;</span>,<span class="string">&quot;http://localhost:4001/&quot;</span>);</span><br><span class="line">            // xhr.setRequestHeader(<span class="string">&quot;content-type&quot;</span>,<span class="string">&quot;multipart/form-data&quot;</span>);</span><br><span class="line">            xhr.send(data);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">function</span> loadHandler(e)&#123;</span><br><span class="line"></span><br><span class="line">         &#125;</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<p>服务端<br>multiparty插件是接收和解析formData表单数据的插件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var http=require(<span class="string">&quot;http&quot;</span>);</span><br><span class="line">var fs=require(<span class="string">&quot;fs&quot;</span>);</span><br><span class="line">var multiparty=require(<span class="string">&quot;multiparty&quot;</span>);</span><br><span class="line"></span><br><span class="line">http.createServer((req,res)=&gt;&#123;</span><br><span class="line">    res.writeHead(200,&#123;</span><br><span class="line">        <span class="string">&quot;content-type&quot;</span>:<span class="string">&quot;text/plain;charset=utf-8&quot;</span>,</span><br><span class="line">        <span class="string">&quot;Access-Control-Allow-Origin&quot;</span>:<span class="string">&quot;*&quot;</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="built_in">let</span> form=new multiparty.Form(&#123;uploadDir:<span class="string">&quot;./&quot;</span>&#125;);</span><br><span class="line">    form.parse(req,<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">        res.writeHead(200,&#123;<span class="string">&quot;content-type&quot;</span>:<span class="string">&quot;text/plain&quot;</span>&#125;);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    form.on(<span class="string">&quot;file&quot;</span>,<span class="keyword">function</span>(name,file)&#123;</span><br><span class="line">       fs.rename(file.path,file.originalFilename,<span class="keyword">function</span>(error)&#123;</span><br><span class="line"></span><br><span class="line">       &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">    res.end();</span><br><span class="line">&#125;).listen(4001);</span><br></pre></td></tr></table></figure>
      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>



  <article>

  
    
    <h3 class="article-title"><a href="/ericxie-book/2021/01/26/path/"><span>path</span></a></h3>
    
  

  <div class="article-top-meta">
    <span class="posted-on">
      <a href="/ericxie-book/2021/01/26/path/" rel="bookmark">
        <time class="entry-date published" datetime="2021-01-26T07:03:18.000Z">
          2021-01-26
        </time>
      </a>
    </span>
  </div>


  

  <div class="article-content">
    <div class="entry">
      
        <h2 id="6、path"><a href="#6、path" class="headerlink" title="6、path"></a>6、path</h2><p>路径主要是为了解决本地路径的拼接所需要的一个方法集</p>
<h3 id="引入path"><a href="#引入path" class="headerlink" title="引入path"></a>引入path</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var path = require(<span class="string">&#x27;path&#x27;</span>);</span><br></pre></td></tr></table></figure>
<h4 id="path-join"><a href="#path-join" class="headerlink" title="path.join"></a>path.join</h4><p>方法使用平台特定的分隔符作为定界符将所有给定的 path 片段连接在一起，然后规范化生成的路径。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf&#x27;</span>);</span><br><span class="line">console.log(str);</span><br></pre></td></tr></table></figure>
<h4 id="path-basename"><a href="#path-basename" class="headerlink" title="path.basename"></a>path.basename</h4><p>返回路径中最后的部分,可以去掉扩展名。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf.txt&#x27;</span>);</span><br><span class="line">console.log(path.basename(str));</span><br><span class="line">console.log(path.basename(str,<span class="string">&quot;.txt&quot;</span>))</span><br></pre></td></tr></table></figure>
<h4 id="path-dirname"><a href="#path-dirname" class="headerlink" title="path.dirname"></a>path.dirname</h4><p>返回路径中目录名</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf.txt&#x27;</span>);</span><br><span class="line">console.log(path.dirname(str));</span><br></pre></td></tr></table></figure>
<h4 id="path-extname"><a href="#path-extname" class="headerlink" title="path.extname"></a>path.extname</h4><p>返回路径中的扩展名</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf.txt&#x27;</span>);</span><br><span class="line">console.log(path.extname(str));</span><br></pre></td></tr></table></figure>
<h4 id="path-parse"><a href="#path-parse" class="headerlink" title="path.parse"></a>path.parse</h4><p>将字符串对象转换为对象</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf.txt&#x27;</span>);</span><br><span class="line">console.log(path.parse(str));</span><br></pre></td></tr></table></figure>
<h4 id="path-format"><a href="#path-format" class="headerlink" title="path.format"></a>path.format</h4><p>将path对象转换为字符串</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var str=path.join(<span class="string">&#x27;/foo&#x27;</span>, <span class="string">&#x27;bar&#x27;</span>, <span class="string">&#x27;baz/asdf.txt&#x27;</span>);</span><br><span class="line">var obj=path.parse(str);</span><br><span class="line">console.log(path.format(obj))</span><br></pre></td></tr></table></figure>
<h4 id="dirname和-filename"><a href="#dirname和-filename" class="headerlink" title="__dirname和__filename"></a>__dirname和__filename</h4><p>本地全局的当前文件夹地址和全局的当前文件路径和文件名</p>

      
    </div>

  </div>

  <div class="article-footer">
    <div class="article-meta pull-left">

    

    

    </div>

    
  </div>
</article>




<nav class="pagination">
  
  
  <a href="/ericxie-book/page/2/" class="pagination-next">Next</a>
  
</nav>
    </main>

    <footer class="site-footer">
  <p class="site-info">
    Proudly powered by <a href="https://hexo.io/" target="_blank">Hexo</a> and
    Theme by <a href="https://github.com/CodeDaraW/Hacker" target="_blank">Hacker</a>
    </br>
    
    &copy; 2021 John Doe
    
  </p>
</footer>
    
    
  </div>
</div>
</body>
</html>